即使我们已经超载了+
和=
运算符,是否有必要过载运算符+=
?超载复合赋值运算符
回答
您打算使用+=
运算符吗?如果是,那么是的,你应该超载它。
即使过载了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+
的一致性。
谢谢你的回答@songyuanyao – Walidix
@WalidSalhi不客气。 – songyuanyao
- 1. 运算符超载赋值运算符
- 2. 赋值=运算符超载
- 3. 复合赋值运算符重载
- 4. java复合赋值运算符和赋值运算符
- 5. MATLAB - 超载赋值运算符
- 6. 混合赋值和复合赋值运算符 - 优先级?
- 7. 重载复制赋值运算符
- 8. 重载赋值运算符
- 9. 重载赋值运算符
- 10. 移动赋值运算符VS拷贝赋值运算符
- 11. 模板类的超载赋值运算符
- 12. 在C++中重载赋值运算符
- 13. TypeScript中的赋值运算符重载
- 14. C++重载赋值运算符
- 15. C++赋值运算符重载
- 16. 重载赋值运算符标操作
- 17. 重载赋值运算符C++
- 18. 重载C++赋值运算符
- 19. 运算符在枚举上为组合赋值运算符重载
- 20. 运算符重载如何为赋值运算符工作?
- 21. 赋值运算符 - 自赋值
- 22. Java复合赋值表达式中的运算符优先级
- 23. 复合赋值运算符可以短路
- 24. 运算符超载[]
- 25. 运算符超载
- 26. 运算符==超载
- 27. 运算符+超载
- 28. 运算符超载
- 29. 运算符超载
- 30. 关于复制构造函数和重载赋值运算符
做加法然后赋值与'+ ='不是一回事。然后最终的结果*可能*是相同的,但不同的事情正在发生。如果任何重载操作符有副作用(有意或无意),这一点尤其重要。 –
谢谢@JoachimPileborg – Walidix