首页 > 解决方案 > 返回对调用对象的引用 (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”?

标签: c++pointersthispass-by-reference

解决方案


如果setX改为

Test setX(int a) { x = a; return *this; }

然后它返回一个副本*this不是对它的引用。所以在

obj1.setX(10).setY(20);

thesetY在副本上调用,而不是在obj1其自身上调用。副本被丢弃,并且obj1.y永远不会从其初始值 5 修改。


推荐阅读