Output of C++ Program | Set 6

  Predict the output of below C++ programs.

Question 1

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

  Output: Compiler Error.

  A const object cannot call a non-const function.

  The above code can be fixed by either making getValue() const or making t non-const. Following is modified program with getValue() as const, it works fine and prints 0.

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


Question 2

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Test 
 5 {
 6     int &t;
 7 public:
 8     Test (int &x) 
 9     { 
10         t = x; 
11     }
12     int getT() 
13     { 
14         return t; 
15     }
16 };
17 
18 int main()
19 {
20     int x = 20;
21     Test t1(x);
22     cout << t1.getT() << " ";
23     x = 30;
24     cout << t1.getT() << endl;
25     return 0;
26 }

  Output: Compiler Error.
  Since t is a reference in Test, it must be initialized using Initializer List.

  Following is the modified program. It works and prints “20 30″.

 1 #include<iostream>
 2  
 3 using namespace std;
 4  
 5 class Test {
 6     int &t;
 7 public:
 8     Test (int &x):t(x) {  }
 9     int getT() { return t; }
10 };
11  
12 int main() {
13     int x = 20;
14     Test t1(x);
15     cout << t1.getT() << " ";
16     x = 30;
17     cout << t1.getT() << endl;
18     return 0;
19 }

  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:27:57

原文地址:https://www.cnblogs.com/iloveyouforever/p/3445793.html