复数complex侯捷大师级写法,声明加定义

复数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) << ',';
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值