Output of C++ Program | Set 5

本文详细解析了C++编程中的几个基础概念,并通过具体实例展示了如何解决常见问题。主要内容包括构造函数的使用、静态变量的应用、类的声明与初始化、函数返回引用等关键点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

  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 \n";
13 }
14 
15 int main()
16 {
17     cout<<"Start \n";
18     Test t1();
19     cout<<"End \n";
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

  

转载于:https://www.cnblogs.com/iloveyouforever/p/3445777.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值