C++ Complex类实现

Complex类是典型的不含指针的类。

下面贴出代码:

#ifndef __COMPLEX_H_
#define __COMPLEX_H_

// a += b += c;     结合律 right -> left
// cout << a << b;  结合律 left  -> right

#include <iostream>

//编译器会生成默认的拷贝构造,拷贝赋值,和析构函数
class Complex {
public:
    Complex(double re = 0, double im = 0) : real(re), imag(im) {}
    Complex& operator+=(const Complex&);
    Complex& operator-=(const Complex&);
    Complex& operator*=(const Complex&);
    Complex& operator/=(const Complex&);

    double getImag() const{
        return this->imag;
    }
    double getReal() const{
        return this->real;
    }

private:
    double real;
    double imag;

    friend Complex& __doapl(Complex*, const Complex&);
    friend Complex& __doami(Complex*, const Complex&);
    friend Complex& __doaml(Complex*, const Complex&);
};

inline Complex&
__doapl(Complex* lhs, const Complex& rhs) {
    lhs->real += rhs.real;
    lhs->imag += rhs.imag;
    return *lhs;
}

inline Complex&
Complex::operator+=(const Complex& rhs) {
    return __doapl(this, rhs);
}

inline Complex&
__doami(Complex* lhs, const Complex& rhs) {
    lhs->real -= rhs.real;
    lhs->imag -= rhs.imag;
    return *lhs;
}

inline Complex& 
Complex::operator-=(const Complex& rhs) {
    return __doami(this, rhs);
}

inline Complex&
__doaml(Complex* lhs, const Complex& rhs) {
    double d = lhs->real * rhs.real - lhs->imag * rhs.imag;
    lhs->imag = lhs->real * rhs.imag + lhs->imag * rhs.real;
    lhs->real = d;
    return *lhs;
}

inline Complex&
Complex::operator*=(const Complex& rhs) {
    return __doaml(this, rhs);
}

std::ostream&
operator<<(std::ostream& os, const Complex& c) {
    os << "(" << c.getReal() << "+" << c.getImag() << "i)" << std::endl;
    return os;
}


#endif //__COMPLEX_H_  

测试程序:

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

int main(int argc, char** argv) {
    Complex c1(2, 1);
    Complex c2(4, 0);

    cout << c1 << endl;
    cout << c2 << endl;

    c1 += c2;

    cout << c1 << "\n";

    return 0;
}

结果:
pic1
另一种含指针的类的实现,见这里

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值