在 C++ 中重载复合赋值运算符

Overloading compound assignment operators in C++

当我们将 += 运算符重载到 return 对 class 的引用时,为什么有必要? 为什么原型是 ClassName& operator += (const ClassName& instance) 而不是
void operator += (const ClassName& instance) ?

几个原因。

这就是内置 += 和朋友所做的;你的重载版本最好在没有真正充分的理由和事实文档的情况下表现得一样,否则使用它的人期望它像内置的那样表现会不高兴。

内置表达式的作用是允许它们用作更大表达式的一部分,例如 a + (b += c)

它使根据 operator+=() 和复制构造函数定义重载 operator+() 变得容易。考虑

class foo {
  foo& operator+=(const foo &b) {
    // Do stuff
    return *this;
  }
};
foo operator+(foo a, const foo &b) { // First argument passed by value, second by reference
  return a += b;
}

使复合运算符 class 成员和普通运算符独立是一种常见的风格建议;它允许第一个参数是不同的类型,只要它可以转换为 foofoo b; foo a = 1 + b;

(为了演示目的,所有示例都非常做作)

这是因为 operator += 必须是 left-hand-expression

例如,在 a += ...; 中,这个表达式的计算结果不可能不是 left-hand-expression(即 a += b + c + d;)。