返回对调用对象的引用 (C++)

Returning a reference to the calling object (C++)

提问人:Ashdeep Singh 提问时间:5/6/2021 更新时间:5/6/2021 访问量:157

问:

有点难以理解这段代码:

#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++ 指针 按引用传递

评论

1赞 alfC 5/6/2021
你的意思是“为什么我们必须作为引用返回,而不仅仅是作为值返回?如果是这样,因为返回一个引用以不断修改原始对象的属性,而不是它的副本。*this*this

答:

3赞 Nate Eldredge 5/6/2021 #1

如果更改为setX

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

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

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

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