重载复合赋值运算符
Overloading compound assignment operator
即使我们已经重载了 +
和 =
运算符,是否还需要重载 +=
运算符?
您要使用 +=
运算符吗?如果是,那么是,你应该重载它。
即使您重载了 operator+
和赋值运算符,编译器也不会自动创建一个。您可以相互实施它们,但它们都需要实施。一般来说,加法和赋值会和复合赋值做同样的事情,但情况并非总是如此。
一般来说,当重载算术运算符(+
、-
等)时,您也应该使用它们相关的复合赋值(+=
、-=
等)。
有关 cppreference 的一些规范实现,请参阅 "Binary arithmetic 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)
}
};
此 SO Q&A 重载的一些基本规则。
是的,一般来说,在实现运算符重载时为内置类型(例如 int
)提供相同的行为是个好主意,以避免混淆。
如果没有 operator+=
,您必须使用 operator+
和 operator=
来做同样的事情。即使使用 RVO,也会应用一次副本。
如果你决定实现operator+=
,为了一致性,最好用它来实现operator+
。
即使我们已经重载了 +
和 =
运算符,是否还需要重载 +=
运算符?
您要使用 +=
运算符吗?如果是,那么是,你应该重载它。
即使您重载了 operator+
和赋值运算符,编译器也不会自动创建一个。您可以相互实施它们,但它们都需要实施。一般来说,加法和赋值会和复合赋值做同样的事情,但情况并非总是如此。
一般来说,当重载算术运算符(+
、-
等)时,您也应该使用它们相关的复合赋值(+=
、-=
等)。
有关 cppreference 的一些规范实现,请参阅 "Binary arithmetic 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) } };
此 SO Q&A 重载的一些基本规则。
是的,一般来说,在实现运算符重载时为内置类型(例如 int
)提供相同的行为是个好主意,以避免混淆。
如果没有 operator+=
,您必须使用 operator+
和 operator=
来做同样的事情。即使使用 RVO,也会应用一次副本。
如果你决定实现operator+=
,为了一致性,最好用它来实现operator+
。