运算符的重载的实质是函数重载
返回值类型 operator 运算符(形参表)
{
……
}
运算符可以重载为普通函数,也可以重载为成员函数
(1)普通函数:重载为普通函数时,参数个数为运算符目数
Complex operator+ (const Complex &a, const Complex &b)
{
return Complex(a.real + b.real, a.imag +b.imag);
}
Complex a(1,2), b(2,3),c;
c=a+b; //相当于 operator+ (a,b)
(2)成员函数:重载为成员函数时,参数个数为运算符目数减1
class Complex
{
public:
Complex(double r =0.0, double m =0.0): real(r), imag(m) { }
Complex operator+(const Complex &); // a+b 相当于a.operator+(b)
Complex operator-(const Complex &);
private:
double real;
double imag;
};
Complex Complex::operator+(const Complex & operand2)
{
return Complex(real + operand2.real, imag+operand2.imag);
}