C++ Complex复数类

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;

class Complex
{
public:
	Complex(double real = 0, double image = 0)
		:_real(real)
		,_image(image)
	{}

	Complex(const Complex& d)
		:_real(d._real)
		,_image(d._image)
	{}

	void Display()
	{
		cout<<"real:"<<_real<<"image:"<<_image<<endl;
	}

	Complex operator +(const Complex& d)//复数相加
	{
		Complex tmp = *this;
		tmp._real += d._real;
		tmp._image += d._image;
		return tmp;
	}

	Complex& operator +=(const Complex& d)//复数的加等,返回值用引用
	{
		_real += d._real;
		_image += d._image;
		return *this;
	}
	
	Complex& operator ++()//复数的前置++,返回值用引用
	{
		_real++;
		return *this;
	}

	Complex operator ++(int)//复数的后置++
	{
		Complex tmp = *this;
		_real++;
		return tmp;
	}

	//减法与加法相似
	//Complex operator -(const Complex& d)
	//Complex& operator -=(const Complex& d)
	//Complex& operator --()
	//Complex operator --(int)

	//复数不能比较大小(复数有方向)所以这里就不实现了^-^
	//operator >
	//operator >=
	//operator <
	//operator <=
	bool operator ==(const Complex& d)//复数的==
	{
		return (_real == d._real)
			&& (_image == d._image);
	}

	bool operator !=(const Complex& d)//复数的!=
	{
		return (_real != d._real)
			|| (_image != d._image);
	}

	Complex operator *(const Complex& d)//复数相乘
	{
		Complex tmp;
		tmp._real = (_real*d._real) - (_image*d._image);
		tmp._image = (_real*d._image) + (_image*d._real);
		return tmp;
	}

	Complex operator /(const Complex& d)//复数相除
	{
		Complex tmp;
		tmp._real= ((_real*d._real) - (_image*d._image))
			      /((d._real)*(d._real) + (d._image)*(d._image));
		tmp._image = (_real*d._image) + (_image*d._real)
				  /((d._real)*(d._real) + (d._image)*(d._image));
		return tmp;
	}

private:
	double _real;
	double _image;
};

void test1()//测试加减相关函数
{
	Complex d1(1, 1);
	Complex d2(2, 2);
	Complex d3;
	d3 = d1 + d2;
	d3.Display();

	d3 = d1++;
	d3.Display();

	d3 = d1+=(d2);
	d3.Display();

	d3 = ++d1;
	d3.Display();
}

void test2()//测试乘除/==/!=
{
	int a = -1;
	Complex d1(1, 1);
	Complex d2(2, 2);
	Complex d3;

	d3 = d1*(d2);
	d3.Display();

	d3 = d1/(d2);
	d3.Display();

	a = d1==(d2);
	cout<<"operator ==():"<<a<<endl;

	a = d1!=(d2);
	cout<<"operator !=():"<<a<<endl;
}
int main()
{
	test1();
	test2();
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值