• 一般情况下重载为成员函数是较好的选择
    • BUT,有时候成员函数不能满足要求,普通函数又不能访问类的成员
      1. class Complex {
      2. double r, i;
      3. public:
      4. Complex(double r_, double i_):r(r_), i(i_){}
      5. Complex operator+(double r);
      6. }
      7. Complex Complex::operator+(double r) { // 能解释 c + 5
      8. return Complex(r + this->r, i);
      9. }
      上面可以应付 c = c+5,但应付不了 c = 5+c,所以可以将+重载为普通函数,同时声明友元
      1. class Complex {
      2. double r, i;
      3. public:
      4. Complex(double r_, double i_):r(r_), i(i_){}
      5. Complex operator+(double r);
      6. friend Complex operator+(double r, const Complex & c);
      7. }
      8. Complex operator+(double r, const Complex & c) {
      9. return Complex(c.r + r, c.i);
      10. }