侯捷C++手把手教学:操作符重载与临时对象

操作符也类比为一种特殊函数。
所有的成员函数都带有一个隐藏的参数,即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) <<')';
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值