zoukankan      html  css  js  c++  java
  • Output of C++ Program | Set 7

      Predict the output of following C++ programs.

    Question 1

     1 class Test1 
     2 {
     3     int y;
     4 };
     5 
     6 class Test2 
     7 {
     8     int x;
     9     Test1 t1;
    10 public:
    11     operator Test1() 
    12     { 
    13         return t1; 
    14     }
    15     operator int() 
    16     { 
    17         return x; 
    18     }
    19 };
    20 
    21 void fun ( int x)  
    22 { 
    23 }
    24 void fun ( Test1 t ) 
    25 { 
    26 }
    27 
    28 int main() 
    29 {
    30     Test2 t;
    31     fun(t);
    32     return 0;
    33 }

      Output: Compiler Error
      There are two conversion operators defined in the Test2 class. So Test2 objects can automatically be converted to both int and Test1. Therefore, the function call fun(t) is ambiguous as there are two functions void fun(int ) and void fun(Test1 ), compiler has no way to decide which function to call.

      In general, conversion operators must be overloaded carefully as they may lead to ambiguity.

    Question 2

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class X 
     5 {
     6 private:
     7     static const int a = 76;
     8 public:
     9     static int getA() 
    10     { 
    11         return a; 
    12     }
    13 };
    14 
    15 int main() 
    16 {
    17     cout <<X::getA()<<endl;
    18     return 0;
    19 }

      Output: The program compiles and prints 76
      

      Generally, it is not allowed to initialize data members in C++ class declaration, but static const integral members are treated differently and can be initialized with declaration.

      Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


      转载请注明:http://www.cnblogs.com/iloveyouforever/

      2013-11-27  15:35:28

  • 相关阅读:
    grunt学习(二)——安装grunt及其插件
    grunt学习(一)——nodejs入门
    18个常用的网站性能测试工具
    JSTL(fn函数)
    为MySQL选择合适的备份方式
    Web开发者文档和手册
    为Ruby On Rails开发者准备的5款IDE
    量子统计
    【日常训练】【ACM】2019-10-27_ccpc2019秦皇岛
    poj 2686 Traveling by Stagecoach
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3445823.html
Copyright © 2011-2022 走看看