gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:28:22 24 4
gpt4 key购买 nike

C++ 中,如果我输入:

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

关于c++ - 通过引用返回在 C++ 类中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23965304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com