复数complex大师级写法,声明加定义
首先防卫式的头文件申明
#ifndef _COMPLEX_
#define _COMPLEX_
class complex
{
public:
complex(double r=0,double i=0) //默认值
:re(r),im(i)
{ }
complex& operator +=(const complex&);
double real () const {return re;} //内联函数
double imag () const {return im;}
private:
double re,im;
friend complex& _doapl(complex*,const complex&);
};
#endif
操作符重载+=,成员函数写法。那么会有隐藏的参数this。
传引用可以提高效率,右边的参数不会改变,加const。
返回值为引用类型,因为左边的参数不属于函数内部。
默认都是inline。
inline complex&
_doapl(complex* ths,const complex& r)
{
ths->re+=r.re;
ths->im+=r.im;
return *ths;
}
inline complex&
complex::operator +=(const complex& r)
{
return _doapl(this,r);
}
非成员函数设计,由于复数涉及到与实数的运算,不仅仅有复数与复数的运算,因此将+设计为非成员函数。
结果是函数内部产生的,即local。因此返回值不能是引用。
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) );
}
inline complex
operator + (double x,const complex& y)
{
return complex ( x + real(y), imag(y) );
}
流运算符<<定义。
#include <iostream.h>
ostream& //返回类型,是为了防止链式调用
operator << (ostream& os,
const complex& x)
{
os << '(' << real(x) << ','
<< imag(x) << ',';
}