为什么赋值运算符应该返回对对象的引用? [英] Why should the assignment operator return a reference to the object?
问题描述
我正在对我的 C++ 进行一些修订,我正在处理运算符重载,特别是="(赋值)运算符.我在网上查找并遇到了多个讨论它的主题.在我自己的笔记中,我把我所有的例子都记为类似
I'm doing some revision of my C++, and I'm dealing with operator overloading at the minute, specifically the "="(assignment) operator. I was looking online and came across multiple topics discussing it. In my own notes, I have all my examples taken down as something like
class Foo
{
public:
int x;
int y;
void operator=(const Foo&);
};
void Foo::operator=(const Foo &rhs)
{
x = rhs.x;
y = rhs.y;
}
在我在网上找到的所有引用中,我注意到操作符返回对源对象的引用.为什么正确的方法是返回对对象的引用而不是完全没有?
In all the references I found online, I noticed that the operator returns a reference to the source object. Why is the correct way to return a reference to the object as opposed to the nothing at all?
推荐答案
通常的形式返回对目标对象的引用以允许赋值链接.否则,这是不可能的:
The usual form returns a reference to the target object to allow assignment chaining. Otherwise, it wouldn't be possible to do:
Foo a, b, c;
// ...
a = b = c;
仍然要记住,正确使用赋值运算符 比它更难可能看起来.
Still, keep in mind that getting right the assigment operator is tougher than it might seem.
这篇关于为什么赋值运算符应该返回对对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!