运算符重载可以友元重载,也可以成员函数重载,但两者是不能共存的。因为这会造成二义性,再一次强调,计算机最讨厌的就是让他做选择。同时有的运算符只支持友元重载,有的则只能成员函数重载,在后面的详细说明中,再区分,先举个例子:
一、友元重载:
class Complex{
private:
float _x;
float _y;
public:
Complex(float x = 0, float y = 0):_x(x), _y(y){}
void dis(){
cout << "( " << _x << "," << _y << " )" << endl;
}
friend Complex operator+(Complex &a, Complex &b){
Complex t;
t._x = a._x + b._x;
t._y = a._y + b._y;
return t;
}
};
可以看到对于双目运算符重载的友元重载参数有两个,并且这里把友元的声明与定义都放在了类中,这样也是可以的。友元的实现位置不重要,但一定要在类中声明。
二、成员函数重载
class Complex{
private:
float _x;
float _y;
public:
Complex(float x = 0, float y = 0):_x(x), _y(y){}
void dis(){
cout << "( " << _x << "," << _y << " )" << endl;
}
Complex operator+(Complex &a){
Complex t;
t._x = this->_x + a._x;
t._y = this->_y + a._y;
return t;
}
friend Complex operator+(Complex &a, Complex &b){
Complex t;
t._x = a._x + b._x;
t._y = a._y + b._y;
return t;
}
};
int main()
{
Complex a(10, 0), b(