如何通过引用返回对象
How works returning an object by reference
据我所知,这是我的参考SomeClass&ref=b;之后b=ref;则c=b;SomeClass&ref2=c;则c=ref2。但是,当b=ref或c=ref2时,我是否正在调用我重新加载的运算符=开关?像那样的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;
}
通过在SomeClass
中重载运算符=,您正在执行复制赋值lhs = rhs
(例如:c = b
,c是lhs
,b是rhs
(。因为它返回一个与SomeClass& operator=
期望的参数类型匹配的引用,所以可以链接多个副本分配,如c = b = a
。
如果您有:
void operator=(const SomeClass& l_copy)
{
this->a = l_copy.a;
}
那么你的任务操作将被限制为:
b = a;
c = b;
通过返回引用,您可以将分配链接为:
c = b = a;
// c.operator = (b.operator = (a));
//1: b.operator= ("ref a")
//2: c.operator= ("ref b")
相关文章:
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 如何访问从 COM 对象返回的 VARIANT 数据类型中的安全数组C++?
- 从我的对象返回静态数组
- 将unique_ptr作为<Object>unique_ptr<常量对象返回>
- 从右值对象返回成员
- 视觉对象 返回 C++ 中的双精度值
- 为什么类型为 sf::Text 的对象返回不同的 getPosition().y 和 getLocalBounds().
- std::min_element 从类对象返回意外结果
- C++无效的对象返回语义
- const引用是否延长临时对象返回的临时对象的寿命
- 将 NULL 作为对象返回时未收到任何警告
- 如何在 C# 中从 com 对象返回数组(double[])
- 从重载运算符返回引用,并使用临时对象返回表达式
- Cin 对象返回值 c++
- 将变量作为类对象返回
- 使用可更改对象返回只读的最佳方法是什么
- 如何在Cython中从另一个包装对象返回包装的c++对象
- 当对象返回时,c++动态数组被清除
- 从带有动态字段的函数、对象返回
- 从堆栈上的匿名对象返回对*this的引用