如果我们已经重载了+
和=
运算符,那么是否有必要重载+=
运算符?
+=
运算符吗?如果是,那么是的,你应该重载它。operator+
和赋值运算符,编译器也不会自动创建+=
运算符。你可以用一个运算符实现另一个运算符,但它们都需要被实现。通常情况下,加法和赋值运算符会像复合赋值运算符一样执行相同的操作,但这并不总是这样。+
、-
等)时,你应该同时重载它们对应的复合赋值运算符(如+=
、-=
等)。
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)
}
};
这里是一些关于重载的基本规则,SO Q&A。
通常,在实现运算符重载时,使用内置类型(如int
)提供相同的行为是一个好主意,以避免混淆。
如果没有operator+=
,则您必须使用operator+
和operator=
来完成相同的操作。即使使用了RVO,仍将应用更多的复制。
如果决定实现operator+=
,最好使用它来实现一致性的operator+
。
+=
进行运算。最终结果可能相同,但发生的事情是不同的。这一点尤其重要,如果任何重载的运算符具有副作用(无论是否有意)。 - Some programmer dude