錯誤認知:
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返回的是當前對象本身(也就是其引用), 而非副本。