返回对调用该函数的对象的引用时,返回的引用可用于链接单个对象上的函数调用.
在这里,我正在应用相同的概念.但是如果我以不同方式初始化对象,我会得到不同的输出.
第一个例子:
#includeusing 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; }
输出为10和20,这是正确的.
但是,第二个示例的输出不正确:
#includeusing 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; obj1.setX(10).setY(20); obj1.print(); return 0; }
输出为10和0.
为什么?我认为两者都是一样的,第二个程序的输出也应该是10和20.它有什么不同?
不同之处在于程序的第二个版本按值返回.这意味着第二次调用(即setY
)是在副本上执行obj1
,而不是在obj1
自身上执行.这就是为什么X
最终只能被设定,但不是Y
.
另一方面,在您的第一个程序中,setter将其结果作为参考返回.这意味着没有复制,因此setY
在同一个对象上调用setX
,而不是在其副本上调用.