重载运算符的基本概念
重载运算符的形式:
- 运算符的重载是函数重载
- 可以重载为普通函数,也可以重载为成员函数
- 把含运算符的表达式转换成对运算符函数的调用
- 把运算符的操作数转换成运算符函数的参数
- 函数被重载多次,参数类型决定调用哪个运算符函数
class complex
{
public:
double real,imag;
complex(double r,double i):real(r),imag(i){}
complex operator-(const complex& c);
}
//普通函数
complex operator+(const complex& a,const complex& b)
{
return complex(a.real + b.real,a.imag + b.imag);
}
//成员函数
complex operator-(const complex& c)
{
return complex(real - c.real,imag - c.imag);
}
重载为成员函数时,参数个数为运算符目数减1
重载为普通函数时,参数个数为运算符目数