引用返回在c++类中是如何工作的

How does return by reference work in C++ classes?

本文关键字:何工作 工作 返回 c++ 引用      更新时间:2023-10-16

C++中,如果i键入:

int x=5;
int &y=x;

y将作为存储原始x的内存位置的别名,这可以通过打印xy的内存位置来证明/测试

类似程序的输出如下:

x is at location: 0x23fe14
y is at location: 0x23fe14

但是呢?

当成员函数声明为返回类型作为引用并且函数使用this指针时,函数实际返回的是什么?例如:

#include <iostream>
class simple
{
    int data;
public:
    // ctor
    simple():
        data(0)
        {}
    // getter function
    int& getter_data()
    {   return this->data;    }
    // modifier functions
    simple& add(int x=5)
    {   this->data += x;
        return *this;
    }
    simple& sub(int x=5)
    {   this->data -= x;
        return *this;
    }
};
int main()
{   simple obj;
    obj.add().sub(4);  ////////// how & why is it working? /////////
    std::cout<<obj.getter_data();
    getchar();
}

为什么可以执行突出显示行的命令?

obj.add()返回给sub()的数据类型是什么?

当你的成员函数返回simple&初始化与*this (*thissimple的一个实例)的语义是相同的作为你自己的"参考示例";引用用该类型的实例初始化。

您正在用对象本身初始化返回的引用。


下面的代码段在语义上是等价的:

obj.add ().sub (4);

<一口>

simple& ref = obj.add ();
ref.sub (4); // `ref` is really `obj`,
             // the address of `ref` and `obj` are the same

obj.add()返回给sub()的数据类型是什么?

obj.add()返回一个对obj实例的引用。

文本"return to The sub() "根本没有意义。

然而,在你的例子中,对对象的引用与指向对象的普通指针非常相似,通常这是一个很好的比喻。