C++学习笔记3 重载操作符

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));
}










 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值