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

包括内容有:

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

形参尽量使用引用

const 能加则比加

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

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

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

构造函数的函数重载

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

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

临时类(Temporary object)

 

代码:

complex.h

#ifndef COMPLEX_H
#define COMPLEX_H

#include 
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 
#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;
}

运行结果:

complex class (复数类的设计,不带指针的class)_第1张图片

你可能感兴趣的:(C++,算法面试题)