在c++ Primer(第五版)的练习题7.27于7.28中,对于this返回值的练习中有疑问,因此参照了博主daimous的一篇博客,但是仍然有些许地方有需要深入理解的地方。
return *this返回的是当前对象的克隆或者本身(若返回类型为A, 则是克隆, 若返回类型为A&, 则是本身 )。
return this返回当前对象的地址(指向当前对象的指针)。
如果返回类型是A&, 那么return *this返回的是当前对象本身(也就是其引用), 而非副本
class Point
{
private:
int x = 0, y = 0;
public:
Point(int a, int b)
:x(a),y(b)
{}
Point add()
{
x=x+1;
y=y+1;
cout << this << endl;
return *this;
}
Point& addR()
{
x=x+1;
y=y+1;
cout << this << endl;
return *this;
}
Point show()
{
cout << x << " " << y << endl;
return *this;
}
};
int main()
{
Point p(10,10);
//cout << &p1 << endl;
p.add().add().show(); //p1.add() 这个整体的返回值作为副本进行下一个add()操作。
p.show(); /*输出为(11,11)而不是(10,10)是因为在执行第一个add()操作时,this指针指代的是原对象,在进行了加1操作后才返回的副本*/
/*上面两行代码show()的结果一个为(12,12),第二个为(11,11)*/
p.addR().addR().show();
p.show();
/*上面两行代码show()的结果都为(13,13)*/
return 0;
}
参考https://blog.youkuaiyun.com/daimous/article/details/78618432