为什么在更改函数返回类型时,c ++代码的输出会发生变化?

bor*_*ree 0 c++

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);
  obj1.setX(10).setY(20);
  obj1.print();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码输出为10 20但是当我更改Test &setXto Test setXTest &setYto 的返回类型时 Test setY,输出变为10 5.任何人都可以解释相同的原因吗?这不是任务分配或与家庭作业有关的任何事情.

Bry*_*hen 6

这完全是临时对象.

在没有返回引用的版本中,即返回类型是Test 您的代码相当于

Test obj1(5, 5);
Test temp1 = obj1.setX(10);
Test temp2 = temp1.setY(20);
// temp2 will have x = 10 and y = 20, but the object is discarded
obj1.print();
Run Code Online (Sandbox Code Playgroud)

正如您所见setY(20),在临时对象上调用,并且丢弃返回的值.所以只有第一个setX(10)实际修改obj1

另一方面,如果返回引用,即返回类型Test &,则不会创建临时.因此,无论setX(10)并且setY(20)会影响原来的对象(obj1),因为该方法被称为同一个对象.