下面给出的程序打印 x = 10 y = 0
#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;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
但是如果我们替换
Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }
和
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
输出是 x = 10 y = 20 谁能解释为什么会这样?