操作符也类比为一种特殊函数。
所有的成员函数都带有一个隐藏的参数,即this。但调用的参数列表里不能写出来,函数里可以用。
返回值最好是引用,防止链式调用,继续传递。
法则:传送者无需知道接受者是以reference形式接收。
下面的函数决不可return_by_reference,因为它们返回的必定是个local object。
inline complex
operator + (const complex& x,const complex& y)
{
return complex(real(x)+real(y),
imag(x)+imag(y));
}
inline complex
operator + (const complex& x,double y)
{
return complex(real(x)+y,imag(x)); //由typename( )所产生的临时对象生命周期到下一行就结束
}
inline complex
operator + (double x,const complex& y))
{
return complex(x+real(y),imag(y));
}
操作符’<<'必须以非成员函数重载,因为对于我们自定义的class,在cout中是不存在的。
#include <iostream.h>
ostream& //防止链式调用
operator << (const& os, const complex& x)
{
return os << '(' << real(x) << ','
<< imag(x) <<')';
}