【问题标题】:Returning a reference to the calling object (C++)返回对调用对象的引用 (C++)
【发布时间】:2021-07-28 08:54:57
【问题描述】:

有点难以理解这段代码:

#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”?

【问题讨论】:

  • 您的意思是“为什么我们必须返回 *this 作为引用而不是仅仅返回 *this 作为值?如果是这样,因为返回引用继续修改原始对象的属性,而不是它的副本。

标签: c++ pointers this pass-by-reference


【解决方案1】:

如果setX 更改为

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

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

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

setY 在副本上调用,而不是在obj1 本身上调用。副本被丢弃,obj1.y 的初始值 5 永远不会被修改。

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多