(1)重载为类的成员函数
格式如下:operator()
class complex
{
public:
complex()
{real=imag=0;}
complex(double r,double
i)
{
real=r;
imag=i;
}
complex operator +(const
complex &c);
complex operator -(const
complex &c);
complex operator *(const
complex &c);
complex operator /(const
complex &c);
private:
double real,imag;
};
inline complex complex::operator+(const complex &c)
{
return
complex(real+c.real,imag+c.imag);
}
inline complex complex::operator-(const complex
&c)
{
return
complex(real-c.real,imag-c.imag);
}
inline complex complex::operator*(const complex
&c)
{
return
complex(real*c.real-imag*c.imag,real*c.imag+imag*c.real);
}
inline complex complex::operator/(const
complex &c)
{
return
complex((real*c.real+imag*c.imag)/(c.real*c.real+c.imag*c.imag),(imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag));
}
有complex c1,c2,c3;
c1+c2表示为c1.operator+(c2)其中operator+()是运算符+的重载函数。
由此得到当运算符重载为成员函数时,双目运算符仅有一个参数。单目运算符重载为成员函数时,不能再显示的说明参数。重载为成员函数时总是隐含一个参数,该参数是this指针。this指针式指向调用该成员函数对象的指针。
(2)重载为类的友元函数
重载为友元函数时,将没有隐含的参数this指针。对双目运算符有两个参数,单目运算符有一个参数
=,(),[],->不宜重载为友元函数。
格式如下:friend operator ()
class complex
{
public:
complex()
{real=imag=0;}
complex(double r,double
i)
{
real=r;
imag=i;
}
friend complex operator +(const
complex &c);
friend complex operator -(const
complex &c);
friend complex operator *(const
complex &c);
friend complex operator /(const
complex &c);
friend void print(const complex
&c);
private:
double real,imag;
};
inline complex complex::operator+(const complex
&c)
{
return
complex(real+c.real,imag+c.imag);
}
inline complex complex::operator-(const complex
&c)
{
return
complex(real-c.real,imag-c.imag);
}
inline complex complex::operator*(const complex
&c)
{
return
complex(real*c.real-imag*c.imag,real*c.imag+imag*c.real);
}
inline complex complex::operator/(const
complex &c)
{
return
complex((real*c.real+imag*c.imag)/(c.real*c.real+c.imag*c.imag),(imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag));
} void print (const complex &c)
{
if (c.imag<0)
cout<
else
cout<
}
此时的c1+c2表示为operator +(c1,c2)
(3)通常单目运算符最好被重载为成员函数,双目运算符最好被重载为友元函数,有些情况下双目运算符不便于重载为友元函数
例如:c+4.45 c是complex对象
+重载为成员函数时有c.operator+(4.45)通过调用构造函数得到c.operator+(complex(4.45))
+重载为友元函数时有operator+(c,4.45)
通过调用构造函数得到operator+(c,complex(4.45))
若是4.45+c
成员函数对应为4.45.operator+(c)//该种方法不对
友元函数对应为operator+(complex(4.45),c)
例如