复合赋值和二元算术: operator+=、operator+

复合赋值和二元算术: operator+=operator+#

定义对应的 复合赋值 版本, 再基于它定义 二元算术:

 1class Widget {
 2 public:
 3  // 复合赋值
 4  Widget& operator+=(Widget const& other) {
 5    value_ += other.value_;
 6    return *this;  // 按引用返回 `*this`
 7  }
 8
 9  // 二元算术
10  friend Widget operator+(Widget const& lhs, Widget const& rhs) {
11    Widget result(lhs);  // 拷贝左参数
12    result += rhs;       // 执行复合赋值运算
13    return result;       // 返回结果
14  }
15
16 private:
17  int value_;
18};

更简单而且会更高效地:

1class Widget {
2 public:
3  friend Widget operator+(Widget const& lhs, Widget const& rhs) {
4    return Widget(lhs) += result;
5    // 1. Widget(lhs)                 : 用 lhs 拷贝构造一个 Widget 类型的临时对象
6    // 2. Widget(lhs) += result       : 对临时对象执行复合赋值运算
7    // 3. return Widget(lhs) += result: 返回临时对象
8  }
9};

或者你也可以反过来, 用 二元运算 定义 复合赋值. 但一般来说, 这样会使复合赋值的实现中使用不必要的 临时对象:

 1class Widget {
 2 public:
 3  // 二元算术
 4  friend Widget operator+(Widget const& lhs, Widget const& rhs) {
 5    Widget result;
 6    result.value_ = lhs.value_ + rhs.value_;
 7    return result;
 8  }
 9
10  // 复合赋值
11  Widget& operator+=(Widget const& other) {
12    *this = *this + other;  // *this + other 会产生一个临时对象
13    return *this;
14  }
15
16 private:
17  int value_;
18};