如何通过引用返回在C ++类中工作?

时间:2014-05-31 00:41:16

标签: c++ class reference return-by-reference

C++中,如果我输入:

int x=5;
int &y=x;

然后y将充当存储原始x的内存位置的别名,并且可以通过打印x和{{的内存位置来验证/测试此内容。 1}}

类似程序的输出如下:

y

呢?

当使用返回类型声明成员函数作为引用并且函数使用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()的哪种数据?

2 个答案:

答案 0 :(得分:3)

当您的成员函数返回simple&初始化为*this*thissimple的实例)时,语义与您自己的&#34;引用相同例如&#34 ;;使用该类型的实例初始化引用

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


以下代码段在语义上是等效的:

obj.add ().sub (4);

simple& ref = obj.add ();

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

答案 1 :(得分:0)

  

什么样的数据是obj.add()返回sub()?

obj.add()正在返回对obj实例的引用。

文字&#34;返回sub()&#34;根本没有意义。

但是,在您的情况下,对象的引用非常类似于指向对象的普通指针,并且通常它是一个很好的元代理。