1. 程式人生 > 程式設計 >淺析C/C++ 中return *this和return this的區別

淺析C/C++ 中return *this和return this的區別

首先我們知道~

class Test
{
public: 
 Test()
 { 
  return this; //返回的當前物件的地址
 }
 Test&()
 { 
  return *this; //返回的是當前物件本身
 }
 Test()
 { 
  return *this; //返回的當前物件的克隆
 }
private: //...
};

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

return this返回當前物件的地址(指向當前物件的指標)

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

#include <iostream>
using namespace std;
class Test
{
public:
 int x;
 Test get()
 {
  return *this; //返回當前物件的拷貝
 }
};
int main()
{
 Test a;
 a.x = 4;
 if(a.x == a.get().x)
 {
  cout << a.x << endl;
    cout << &a << endl;
    cout << &a.get() <<endl;
 }
 else
 {
  cout << "no" << endl;
    cout << &a << endl;
    cout << &a.get() <<endl;
 }

 return 0;
}

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

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

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

所有要注意!

下面談談[C++]類成員返回語句 return *this 的理解

經常會在類似 copy-assignment 的成員函式看到返回語句 return *this,這類函式通常返回型別是所屬類的引用。

類成員函式的隱式指標 class *this const 經過 *this的解引用後成為此物件本身。此時若成員函式返回型別是 class ,那麼返回的將是 this 指向的物件實體的拷貝;

若返回型別是 class& ,那麼將返回一個繫結在 this 指向的物件實體上的引用。

總結

以上所述是小編給大家介紹的C/C++ 中return *this和return this的區別,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!