return *this 和 return this差別
return *this傳回的是目前對象的克隆或者本身(若傳回類型為A, 則是克隆, 若傳回類型為A&, 則是本身 )。return this傳回目前對象的位址(指向目前對象的指針)
#include <iostream>
using namespace std;
class A
{
public:
int x;
//傳回目前對象本身
A& get()
{
return *this;
}
//傳回目前對象的克隆
A get_a()
{
return *this; //傳回目前對象的拷貝
}
//傳回指向目前對象的指針,即目前對象的位址
A* get_b() {
return this;
}
};
int main()
{
A a;
a.x = 4;
//test&(){return *this}
if (&a == &a.get())
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
//test(){return *this}
if (&a == &a.get_a())
{
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
//test* (){retun this};
if (&a == a.get_b())
{
//cout << a.get_b() << endl;
cout << "yes" << endl;
}
else
{
cout << "no" << endl;
}
return 0;
}
yes
no
yes
參考文章:
[1]https://zhuanlan.zhihu.com/p/87363268
[2]https://blog.csdn.net/stpeace/article/details/22220777