如何通过引用返回对象

How works returning an object by reference

本文关键字:对象 返回 引用 何通过      更新时间:2023-10-16

据我所知,这是我的参考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")