C++中this與*this的區別

錯誤認知:

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

正確答案爲:

return *this返回的是當前對象的克隆或者本身(若返回類型爲A, 則是克隆, 若返回類型爲A&, 則是本身 )。return this返回當前對象的地址(指向當前對象的指針), 下面我們來看看程序吧:
#include <iostream>  
using namespace std;  
  
class A  
{  
public:  
    int x;  
    A* get()  
    {  
        return this;  
    }  
};  
  
int main()  
{  
    A a;  
    a.x = 4;  
  
    if(&a == a.get())  
    {  
        cout << "yes" << endl;  
    }  
    else  
    {  
        cout << "no" << endl;  
    }  
  
    return 0;  
}  

結果爲:yes

再看:

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

結果爲:no

最後, 如果返回類型是A&, 那麼return *this返回的是當前對象本身(也就是其引用), 而非副本。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章