c++ - 通过引用返回对象的工作原理
问题描述
据我了解,这是我的参考 SomeClass &ref=b; 之后 b = ref; 然后 c = b; 某类 &ref2=c; 然后 c=ref2 。但是当 b=ref 或 c = ref2 时,我是否调用了 operator = 女巫我已经重新加载?类似的东西 a.operator=(ref) ?
class SomeClass
{
public:
SomeClass()
{
a = 5;
}
SomeClass(int l_a)
{
a = l_a;
}
SomeClass& operator=(const SomeClass& l_copy)
{
this->a = l_copy.a;
return *this;
}
int a;
};
int main()
{
SomeClass a;
SomeClass b(1);
SomeClass с(6);
с = b = a;
}
解决方案
通过重载 operator = in SomeClass
,您正在执行复制赋值lhs = rhs
(例如 : c = b
、 c islhs
和 b is rhs
)。因为它返回与预期参数类型匹配的引用SomeClass& operator=
,所以您可以链接多个复制分配,例如c = b = a
.
推荐阅读
- html - 嵌入网站时如何仅循环播放我的 youtube 频道中的视频
- tensorflow - 为什么 Keras Embedding 层的 input_dim = vocab_size + 1
- angular - 如何将 Angular 部署到 IIS 并通过域名而不是域名和应用名称访问应用
- amazon-web-services - 如何将 AWS EFS 卷附加到 EC2 现货实例?
- node.js - AWS 用户数据无法在 Windows Server 2019 上运行
- stata - 如何在 Stata 中为 X 轴创建一个时间变量,以 1920 为年(0)?
- javascript - 如何从其他数组的数字位置获取数组?
- c# - 剪贴板:复制和接收数组
- node.js - Discord Music Bot没有播放问题
- c# - 在 ASP.NET Core 中扩展 IIdentity 接口