【侯捷--面向对象高级开发】笔记

操作符重载

通过成员函数实现操作符重载

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

在上面_doapl中返回的声明说的是返回一个reference但是最后返回的是一个指针(也就是一个指针指向的对象,return value),这里就是return reference 的一个好处,传递者无需知道接收端为什么形式(value 或者是 reference)
如果将其改为

inline complex*

那么传递者就必须知道接收端需要一个指针类型
再看运算符重载的部分,如果只是c1+=c2,那么写成inline voidcomplex::operator += (const complex& r)即可但是设计者考虑到了 c1+=c2+=c3这种情况

非成员函数实现操作符重载

//c2 = c1 + c3;
inline complex
operator + (const complex& x, const complex& y)
{
  return complex (real (x) + real (y), imag (x) + imag (y));
}
//c1 = c1 + 7;
inline complex
operator + (const complex& x, double y)
{
  return complex (real (x) + y, imag (x));
}
//c1 = 7 + c1;
inline complex
operator + (double x, const complex& y)
{
  return complex (x + real (y), imag (y));
}

与成员函数的区别是此时没有this,此时都是全局函数return by reference好,但此时却是return by value,这是为什么?上面+=是右边的东西加到左边身上,此时左边已经存在了,但现在是两个东西相加,所得到的是一个临时对象,这个临时对象给谁呢?也就是此时在函数里面创建一个对象等于这个临时对象,此时如果把引用当作返回值,那将访问到被回收的内存而导致程序异常出错。

inline complex
operator + (const complex& x)
{
  return x;
}

inline complex
operator - (const complex& x)
{
  return complex (-real (x), -imag (x));
}

上面者两个操作符重载就是不是加减而是正负了,通过参数的个数可以知道与上面的加法不同

ostream&
operator << (ostream& os, const complex& x)
{
  return os << '(' << real (x) << ',' << imag (x) << ')';
}

这种操作符只能选择全局的写法,同时不能写成const,尽管感觉里面并没有改变什么,但是实际上x传进来的改变了os的状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值