提问人:Ashdeep Singh 提问时间:5/6/2021 更新时间:5/6/2021 访问量:157
返回对调用对象的引用 (C++)
Returning a reference to the calling object (C++)
问:
有点难以理解这段代码:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
为什么我们必须返回“*this”作为引用,而不仅仅是返回“*this”?
答:
3赞
Nate Eldredge
5/6/2021
#1
如果更改为setX
Test setX(int a) { x = a; return *this; }
然后,它返回 的副本,而不是对它的引用。所以在*this
obj1.setX(10).setY(20);
在副本上调用,而不是在它自身上调用。副本将被丢弃,并且永远不会修改其初始值 5。setY
obj1
obj1.y
评论
*this
*this