C/C++ return *this和return this的區別


首先我們知道~

 1 class Test
 2 {
 3  public: 
 4     Test()
 5     { 
 6       return this;  //返回的當前對象的地址
 7     }
 8     Test&()
 9     { 
10       return *this;  //返回的是當前對象本身
11     }
12     Test()
13     { 
14       return *this;   //返回的當前對象的克隆
15     }
16  private:  //...
17 };

return *this返回的是當前對象的克隆或者本身(若返回類型為A, 則是拷貝, 若返回類型為A&, 則是本身 )。

return this返回當前對象的地址(指向當前對象的指針)

我們再來看看返回拷貝那個的地址~

 1 #include <iostream>
 2 using namespace std;
 3 class Test
 4 {
 5 public:
 6     int x;
 7     Test get()
 8     {
 9         return *this; //返回當前對象的拷貝
10     }
11 };
12 int main()
13 {
14     Test a;
15     a.x = 4;
16     if(a.x == a.get().x)
17     {
18         cout << a.x << endl;
19                 cout <<  &a << endl;
20                cout << &a.get() <<endl;
21     }
22     else
23     {
24         cout << "no" << endl;
25                 cout <<  &a << endl;
26                cout << &a.get() <<endl;
27     }
28 
29     return 0;
30 }

由運行結果得知會報下列錯誤!!!

cpp [Error] taking address of temporary [-fpermissive]

這是因為引用了臨時對象的地址而引發的警報 臨時對象不可靠……

所有要注意!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM