1. 程式人生 > >C++——類的成員函數的連續調用與返回值問題

C++——類的成員函數的連續調用與返回值問題

code space 不可 std 對象 語句 ios ostream this

一、返回值問題

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class X
 6 {
 7 public:
 8     int a = 3;
 9     X set1(int b)
10     {
11         a = b;
12         return *this;
13     }
14 };
15 
16 int main()
17 {
18     X x;
19     x.set1(6);
20     cout << x.a;
21 
22     return 0;
23 }

此處set1函數的返回值為X,而非X&,所以x.set1(6)返回的是x的一個副本,並非x對象本身,但是return之前的語句,即此處的a = b,仍是對x對象本身進行操作的(因為是對象x調用的此函數,即此處的a仍為x.a,因為a不可能是憑空拷貝出來的),只是返回值為x對象的副本而已,所以x.a的值仍然被修改為了6.

二、連續調用問題

(1)set1與set2的返回值是引用

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class X
 6 {
 7 public:
 8     X display()
9 { 10 cout << a; 11 return *this; 12 } 13 X& set1(int b) 14 { 15 a = b; 16 return *this; 17 } 18 19 X& set2(int b) 20 { 21 a = b; 22 return *this; 23 } 24 25 private: 26 int a = 3; 27 }; 28 29 int main()
30 { 31 X x; 32 x.set1(6).set2(7).display(); 33 cout << “ ”; 34 x.display(); 35 36 37 return 0; 38 39 }

如果set1與set2的返回值是引用,那麽

x.set1(6).set2(7).display(); //等價於x.set1(6); x.set2(7); x.display();

所以此處輸出為:7 7

(2)set1與set2的返回值不是引用

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class X
 6 {
 7 public:
 8     X display()
 9     {
10         cout << a;
11         return *this;
12     }
13     X set1(int b)
14     {
15         a = b;
16         return *this;
17     }
18 
19     X set2(int b)
20     {
21         a = b;
22         return *this;
23     }
24 
25 private:
26     int a = 3;
27 };
28 
29 int main()
30 {
31     X x;
32     x.set1(6).set2(7).display(); 
33     cout << “ ”;
34     x.display();
35 
36 
37     return 0;
38 
39 }

如果set1與set2的返回值是引用,那麽

x.set1(6).set2(7).display(); //不等價於x.set1(6); x.set2(7); x.display(); 此時後面的.set2(7).display()是對x.set1(6)返回的副本進行操作,所以此處只有x.set1(6)對原對象的值進行了操作

故此處輸出為:7 6

C++——類的成員函數的連續調用與返回值問題