实现复数类及简单操作

复数类

复数包含实部和虚部,表示为: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; 
};



全部评论

相关推荐

02-15 09:23
已编辑
深圳技术大学 Java
德勤 后端 OC 实习140/天,转正税前7k
恶龙战士:不如码农烧烤
点赞 评论 收藏
分享
野猪不是猪🐗:是我导致的,我前天对力扣进行了跨站脚本攻击,网站把我的请求给block了(胡言乱语)
点赞 评论 收藏
分享
01-14 12:08
门头沟学院 Java
神哥了不得:(非引流)1.既然发出来了简历,就稍微提一点点小建议,确实简历很不错了,练手项目可以换一些质量高的,工作内容,可以加上一些量化指标,比如第一条系统响应速度由多少变成多少,减少了百分之多少,第4条就很不错。2.广投,年前实习招募比较少了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
02-14 11:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务