operator+声明为成员函数时交换律问题
class Complex
{
public:
Complex() {real = 0; imag = 0;} //默认构造函数
Complex(double r) { real = r; imag = 0;} //转换构造函数
Complex(double r, double i) {real = r; imag = i;} //带参数构造函数
Complex operator+(Complex c2); ///重载‘+’运算符设为成员
void display();
private:
double real;
double imag;
};
//将运算符'+'函数重载为成员函数
Complex Complex::operator+(Complex c2)
{
return Complex(this->real + c2.real, this->imag + c2.imag);
}
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1 + 2.5; ///c3=c1.operator+(Complex(2.5)),隐式将2.5转换为对象
c3 = Complex(2.5) + c1; ///ok
c3 = 2.5 + c1; ///error?
c3.display();
return 0;
}