引用返回在c++类中是如何工作的
How does return by reference work in C++ classes?
在C++
中,如果i键入:
int x=5;
int &y=x;
则y
将作为存储原始x
的内存位置的别名,这可以通过打印x
和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()
返回给sub()
的数据类型是什么?
当你的成员函数返回simple&
初始化与*this
(*this
是simple
的一个实例)的语义是相同的作为你自己的"参考示例";引用用该类型的实例初始化。
您正在用对象本身初始化返回的引用。
下面的代码段在语义上是等价的:
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()
"根本没有意义。
然而,在你的例子中,对对象的引用与指向对象的普通指针非常相似,通常这是一个很好的比喻。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?