0.成员函数
//操作符重载1.成员函数
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&);
};
c2 += c1; //c2就是this,c1是r
/*
inline complex&
complex::operator += (this, const complex& r) //此处是为了方便理解,实际编程中,this是不写的
{
return _doapl (this, r);
}
*/
//标程
inline complex&
_doapl(complex* ths, const complex& r) doapl = do assignment plus 赋值加法
{
ths->re += r.re;
ths->im += r.im;
return *ths; //返回指针所指的东西,但是函数类型是complex&,可以这样写吗?
// 可以,应为return by reference时,传递者无需知道接收者是以reference形式接受,也即是说,不管你传的是什么,它自动转化为引用返回
}
inline complex& //对于返回类型的说明,c2 += c1,加完就完了,没有人关心返回值是什么,所以从某个角度,你把返回类型定义成void也没有错,但是,如果出现连加
complex::operator += (const complex& r) //c3 += c2 += c1(c1先加到c2上,c2再加到c3上) 就需要定义返类型为complex&了
{
return _doapl(this, r);
}
1.非成员函数
//操作符重载2 非成员函数
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&);
};
{
complex c1(2, 1);
complex c2;
}
//为了应对client的三种可能用法,这里对应开发三个对应函数
inline complex //这些函数绝不可return by reference, 因为它们返回的必定是local object,就是加好以后要创建一个临时变量存放结果,这个变量再函数调用结束后会被销毁,如果传引用的话,变量被销毁,再使用引用是要出错的
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));
}
inline complex
operator + (const complex& x)
{
return x;
}
inline complex
operator - (const complex& x)
{
return complex (-real(x), -imag(x));
}