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

     

      Difficulty Level: Rookie

      Predict the output of below C++ programs.

    Question 1

     1 #include<iostream>
     2 using namespace std;
     3 
     4 class Test 
     5 {
     6     int value;
     7 public:
     8     Test(int v);
     9 };
    10 
    11 Test::Test(int v) 
    12 {
    13     value = v;
    14 }
    15 
    16 int main() 
    17 {
    18     Test t[100];
    19     return 0;
    20 }

      Output: Compiler error

      The class Test has one user defined constructor “Test(int v)” that expects one argument. It doesn’t have a constructor without any argument as the compiler doesn’t create the default constructor if user defines a constructor (See this).

      Following modified program works without any error.

     1 #include<iostream>
     2 using namespace std;
     3 
     4 class Test 
     5 {
     6     int value;
     7 public:
     8     Test(int v = 0);
     9 };
    10 
    11 Test::Test(int v) 
    12 {
    13     value = v;
    14 }
    15 
    16 int main() 
    17 {
    18     Test t[100];
    19     return 0;
    20 }


    Question 2

     1 #include<iostream>
     2 using namespace std;
     3 int &fun() 
     4 {
     5     static int a = 10;
     6     return a;
     7 }
     8 
     9 int main() 
    10 {
    11     int &y = fun();
    12     y = y +30;
    13     cout << fun();
    14     return 0;
    15 }

      Output: 40
      The program works fine because ‘a’ is static. Since ‘a’ is static, memory location of it remains valid even after fun() returns. So a reference to static variable can be returned.

     

    Question 3

     1 #include<iostream>
     2 using namespace std;
     3 
     4 class Test
     5 {
     6 public:
     7     Test();
     8 };
     9 
    10 Test::Test()  
    11 {
    12     cout<<"Constructor Called 
    ";
    13 }
    14 
    15 int main()
    16 {
    17     cout<<"Start 
    ";
    18     Test t1();
    19     cout<<"End 
    ";
    20     return 0;
    21 }

      Output:
      Start
      End

      Note that the line “Test t1();” is not a constructor call. Compiler considers this line as declaration of function t1 that doesn’t recieve any parameter and returns object of type Test.

      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:23:22

      

  • 相关阅读:
    浏览器版本过低
    虚拟PWN初探
    elasticsearch常用查询
    python安装pip模块
    spark-kafka-es交互 优化
    scala写文件
    python unittest
    scala collection(集合)
    spark-kafka-es交互
    scala语法
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3445777.html
Copyright © 2011-2022 走看看