为什么赋值操作符返回对象的引用? [英] 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;
}
$ b $ p在我在网上找到的所有引用中,我注意到操作符返回一个引用到源对象。
为什么是正确的方法返回一个对象的引用,而不是没有什么?
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屋!