return *this和return this有什麼區別
return *this返回的是當前物件的克隆或者本身(若返回型別為A, 則是克隆, 若返回型別為A&, 則是本身 );
return this返回當前物件的地址(指向當前物件的指標)。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;
}
結果為:
4
no