自定义实现Complex类

// complex.h
// 防卫式的宏定义
#ifndef __COMPLEX__
#define __COMPLEX__

/* forward declarations */
using std::ostream;
class Complex;

Complex&
__doapl(Complex*, const Complex&);

/* class declarations */
class Complex
{
public:
    Complex(double r = 0, double i = 0) : re(r), im(i) {}
    double real() const {return re;}
    double imag() const {return im;}
    Complex& operator += (const Complex&);
private:
    double re, im;
    
    friend Complex& __doapl(Complex*, const Complex&);
};

/* class definition */
inline Complex&
__doapl(Complex* ths, const Complex& r) {
    ths->re += r.re;
    ths->im += r.im;
    return *ths;
}

// 成员函数作用在左值, a+=b => a.operator+=(b)
// 建议编译器使用inline
// 为了可以连续使用+=, 因此返回值是Complex&, 不是void
inline Complex&
Complex::operator += (const Complex& r) {
    return __doapl(this, r);
}

// 如果写成成员函数就需要写成 complex<<cout
// 因此需要写成全局函数, 第一个是ostream对象(会被改变), 第二个参数是需要输出的
ostream&
operator << (ostream& os, const Complex& c) {
    return os<<"("<<c.real()<<","<<c.imag()<<")";
}

// 如果把+运算符重载设计成成员函数, 那么只能实现complex+一个数, 不能实现一个数+complex
// 因为成员函数是作用于左值的, 所以complex必须在左边
inline Complex
operator + (const Complex& c1, const Complex& c2) {
    return Complex(c1.real() + c2.real(),
                   c1.imag() + c2.imag());
}

inline Complex
operator + (const Complex& c1, double d) {
    return Complex(c1.real() + d, c1.imag());
}

inline Complex
operator + (double d, const Complex& c1) {
    return Complex(c1.real() + d, c1.imag());
}


inline Complex
operator + (const Complex& c) {
    return c;
}

inline Complex
operator - (const Complex& c) {
    return Complex(-c.real(), -c.imag());
}

inline bool
operator == (const Complex& l, const Complex& r) {
    return (l.real() == r.real()) && (l.imag() == r.imag());
}

inline bool
operator != (const Complex& l, const Complex& r) {
    return (l.real() != r.real()) || (l.imag() != r.imag());
}

inline Complex
conj (const Complex& c) {
    return Complex(c.real(), -c.imag());
}

#endif

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

int main() {
	Complex c1(2,1);
    Complex c2;
    cout<<c1<<endl;
    cout<<c2<<endl;
    
    c2 = c1 + 5;
    c2 = 7 + c1;
    c2 = c1 + c2;
    c2 += c1;
    c2 += 3;
    cout<<c2<<endl;
    c2 = -c1;

    cout<<(c1 == c2)<<endl;
    cout<<(c1 != c2)<<endl;
    cout<<conj(c2)<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值