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

      

  • 相关阅读:
    Linux日常之命令sort
    Linux日常之命令sed
    Linux日常之命令grep
    Linux日常之命令awk
    Linux日常之命令tee
    Linux日常之数据重定向
    Hibernate打印SQL及附加参数
    使用D3 Geo模块画澳大利亚地图
    基于Spring-WS的Restful API的集成测试
    做项目时需要考虑的安全性问题
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3445777.html
Copyright © 2011-2022 走看看