据我了解,这是我的引用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
中的operator =,您正在执行复制分配lhs = rhs
(例如:c = b
,c为lhs
和b为rhs
)。因为它返回与SomeClass& operator=
预期参数类型匹配的引用,所以您可以链接多个副本分配,例如c = b = a
。
关于c++ - 如何通过引用返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60277109/