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