C++ 运算符重载复数类的实现

复数类

#pragma once
#ifndef __COMPLEX__
#define __COMPLEX__
#include<iostream>
using namespace std;
class my_complex
{
private:
	double re, im;
	friend my_complex& __doapl(my_complex*, const my_complex &);

public:
	my_complex(double r = 0, double i = 0) :
		re(r), im(i)
	{};
	my_complex& operator+= (const my_complex&);
	double real() const { return re; }
	double imag() const { return im; }

};

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

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

inline double
real(const my_complex& x)
{
	return x.real();
}

inline double
imag(const my_complex &x)
{
	return x.imag();
}

inline my_complex
operator + (const my_complex& x, const my_complex& y)
{
	return my_complex(real(x) + real(y),
		imag(x) + imag(y));

}

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


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

inline my_complex
operator + (const my_complex& x)
{
	return x;
}

inline my_complex
operator - (const my_complex& x)
{
	return my_complex(-real(x), -imag(x));
}

ostream& operator<< (ostream& os, const my_complex& x)
{
	return os << '(' << real(x) << ','
		<< imag(x) << ')';
}

inline bool
operator == (const my_complex& x, const my_complex& y)
{
	return real(x) == real(y) && imag(x) == imag(y);
}

inline bool
operator == (const my_complex& x, double y)
{
	return real(x) == y && imag(x) == 0;
}

inline bool
operator == (double x, const my_complex& y)
{
	return real(y) == x && imag(y) == 0;
}

inline my_complex
conj(const my_complex& x)
{
	return my_complex(x.real(), -x.imag());
}


#endif

测试主程序

#include "Mycomplex.h"

int main()
{
	my_complex c1(2, 1);
	my_complex c2;
	cout << c1 << endl;
	cout << c2 << endl;

	c2 = c1 + 5;
	c2 = 7 + c1;
	c2 = c1 + c2;
	c2 += c1;
	c2 += 3;
	cout << (c1 == c2) << endl;
	cout << conj(c1) << endl;
	return 0;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值