【发布时间】:2021-07-28 08:54:57
【问题描述】:
有点难以理解这段代码:
#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”?
【问题讨论】:
-
您的意思是“为什么我们必须返回
*this作为引用而不是仅仅返回*this作为值?如果是这样,因为返回引用继续修改原始对象的属性,而不是它的副本。
标签: c++ pointers this pass-by-reference