別跟我說勘伺, return *this返回當(dāng)前對(duì)象锥惋, return this返回當(dāng)前對(duì)象的地址(指向當(dāng)前對(duì)象的指針)昌腰。
正確答案為:return *this返回的是當(dāng)前對(duì)象的克隆或者本身(若返回類型為A, 則是克隆膀跌, 若返回類型為A&遭商, 則是本身 )。return this返回當(dāng)前對(duì)象的地址(指向當(dāng)前對(duì)象的指針), 下面我們來看看程序吧:
#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;
}
結(jié)果為:yes
再看:
#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;
}
結(jié)果為:
4
no
最后捅伤, 如果返回類型是A&劫流, 那么return *this返回的是當(dāng)前對(duì)象本身(也就是其引用), 而非副本。