在 C++ 中重载扩充赋值(return 类型)
Overloading augmented assignment in c++ (return type)
我正在制作一个使用 += 操作的对象。应该重载 return 引用 *this
还是应该只是 return *this
?
http://en.cppreference.com/w/cpp/language/operators
在那里你可以找到规范实现。
class X
{
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
假设 foo
和 bar
是 Foo
的实例。
如果+=
没有return引用,那么表达式
foo += bar += bar
在句法上是无效的,这与内置类型背道而驰(尽管有趣的是,这种表达式对内置类型的行为是未定义的,因为 +=
不是排序为此类类型点。)。
不 return 引用也可能导致更多地使用 Foo
的复制构造函数。
快速回答:return 非 const
参考。
我正在制作一个使用 += 操作的对象。应该重载 return 引用 *this
还是应该只是 return *this
?
http://en.cppreference.com/w/cpp/language/operators
在那里你可以找到规范实现。
class X
{
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
假设 foo
和 bar
是 Foo
的实例。
如果+=
没有return引用,那么表达式
foo += bar += bar
在句法上是无效的,这与内置类型背道而驰(尽管有趣的是,这种表达式对内置类型的行为是未定义的,因为 +=
不是排序为此类类型点。)。
不 return 引用也可能导致更多地使用 Foo
的复制构造函数。
快速回答:return 非 const
参考。