实现复数类及简单操作

复数类

复数包含实部和虚部,表示为:a+bi 的形式

复数可以比较两个复数的大小;

两个复数是否相等;

复数前置后置自增自减等操作。

#include <iostream>
using namespace std;


class Complex 
{ 
public: 
	//四个默认成员函数 
	//构造函数 
	Complex(double real=0.0, double image=0.0) 
	{ 
		_real = real; 
		_image = image; 
	} 
	//拷贝构造函数 
	Complex(const Complex& c) 
	{ 
		_real = c._real; 
		_image = c._image; 
	} 
	//析构函数 
	~Complex() 
	{ 
		cout<<"析构函数"<<endl;
	} 
	//赋值操作符的重载 
	Complex& operator=(const Complex& c) 
	{ 
		_real = c._real;
		_image = c._image;
		return *this;
	} 
public: 
	Complex operator+(const Complex& c)
	{
		Complex tmp = 0;
		tmp._real = _real + c._real;
		tmp._image = _image + c._image;
		return tmp;
	}
	Complex& operator+=(const Complex& c)
	{
		_real = _real + c._real;
		_image = _image + c._image;
		return *this;
	}

	Complex operator-(const Complex& c)
	{
		Complex tmp = 0;
		tmp._real = _real - c._real;
		tmp._image = _image - c._image;
		return tmp;
	}
	Complex& operator-=(const Complex& c)
	{
		_real = _real - c._real;
		_image = _image - c._image;
		return *this;
	}

	bool operator==(const Complex& c)
	{
		if((_real == c._real)&&(_image == c._image))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	bool operator!=(const Complex& c)
	{
		if((_real == c._real)&&(_image == c._image))
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	//前置++ 
	Complex& operator++() 
	{ 
		this->_real++; 
		this->_image++; 
		return *this; 
	} 
	//后置++ 
	Complex operator++(int) 
	{ 
		Complex tmp(*this); 
		this->_real++; 
		this->_image++; 
		return tmp; 
	} 

	//前置--
	Complex& operator--() 
	{ 
		this->_real--; 
		this->_image--; 
		return *this; 
	} 
	//后置-- 
	Complex operator--(int) 
	{ 
		Complex tmp(*this); 
		this->_real--; 
		this->_image--; 



测试代码如下:


int main()
{
	Complex c1(3.0,5.0);
	Complex c2(3.0,5.0);
	Complex tmp(0.0,0.0);
	//tmp = c1+c2;     //tmp = c1.operator+(c2)   +运算符重载
	//c1+=c2;          //c1 = c1.operator+=(c2)   +=运算符重载
	//tmp = c1-c2      //tmp = c1.operator-(c2)   -运算符重载
	//c1-=c2;            //c1 = c1.ioerator-=(c2)   -=运算符重载		
	/*if(c1==c2)      // ==判断两个复数类对象是否相等
	{
		cout<<"相等"<<endl;
	}
	else
	{
		cout<<"不等"<<endl;
	}*/
	tmp = c1++;   //后置++
	tmp = ++c1;   //前置++
	tmp = c1--;   //后置--
	tmp = --c1;   //前置--
	c1.Display();
	c2.Display();
	tmp.Display(); 
	return 0;
}


		return tmp; 
	} 
	void Display() 
	{ 
		cout<<_real<<"+"<<_image<<"i"<<endl;
	} 
private: 
	double _real; 
	double _image; 
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值