complex class (复数类的设计,不带指针的class)

包括内容有:

合理使用:引用、const关键字

形参尽量使用引用

const 能加则比加

运算符重载(一般设定为inline函数)

友元函数:可直接使用类的private成员,提高程序运行效率

尽量使用  冒号(:)的赋值方式对 构造函数进行初始化

构造函数的函数重载

类内定义的函数 == inline函数

何时采用成员函数、何时采用全局函数

临时类(Temporary object)

 

代码:

complex.h

#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>
using namespace std;

class complex
{
public:
    complex(double r = 0, double i = 0)
        : re(r), im(i)
    { }
    complex& operator += (const complex&);
    double real() const { return re;}  // inline function
    double imag() const { return im;}  // inline function
private:
    double re, im;

    friend complex& __doapl(complex*, const complex&);  // global function
};



#endif // COMPLEX_H

complex.cpp

#include "complex.h"

// Assignment plus
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);
}

// three cases of add
inline complex
operator + (const complex& x, const complex& y)
{
    return complex(x.real() + y.real(),
                   x.imag() + y.imag());  // Temporary object
}

inline complex
operator + (const complex& x, const double y)
{
    return complex(x.real() + y, x.imag());
}

inline complex
operator + (const double x, const complex& y)
{
    return complex(x + y.real(), y.imag());
}

// overload operator <<
inline ostream&
operator <<(ostream& os, const complex& x)
{
    return os << "(" << x.real() << ","
              << x.imag() << ")";
}

main.cpp

#include <iostream>
#include "complex.h"
#include "complex.cpp"
using namespace std;



int main()
{
    complex x(2, 3);
    complex y(1, 2);

    x += 3;
    cout << x << endl;

    y = y +1;
    cout << y << endl;

    y = 1 + y;
    cout << y << endl;

    complex z;
    cout << z << endl;

    z = x + y;
    cout << z << endl;

    return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值