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

  • 相关阅读:
    Java 包装类
    CTF 入门笔记
    Java 实践
    Java Object类
    Java 接口
    Java 抽象类
    Java 关键字final
    Java 多态性
    C#类,对象,类成员简介
    C#初始类和命名空间
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3445823.html
Copyright © 2011-2022 走看看