[置顶] 复数类的四则运算

问题描述:

    创建一个Plural(复数)的class类,不借助系统的默认成员函数,在类体中写入构造函数,析构函数,拷贝复制函数以及运算符重载函数。并依次实现复数的大小比较(bool)和复数的四则运算(+,-,*,/)。



#include<iostream>
using  namespace std;

class Plural<span style="white-space:pre">		</span>//构建复数类
{
public:
	void  Display()
	{
		cout << "Real->:" << _real;
		cout << " Image->:" << _image << endl;
	}

public:
	Plural(double  real = 1.0, double image = 1.0)//复数的实部和虚部存在小数情况,所以用double表示
	{
		_real = real;
		_image = image;
	}


	Plural(Plural& a)<span style="white-space:pre">	</span>//拷贝构造函数,注意引用符,若为值传递则可能会引发无穷递归
	{
		_image = a._image;
		_real = a._real;
	}


	Plural& operator =(const Plural& c)//返回值可实现链式访问,不改变原有值,则加const修饰符,使其返回值成为左值
	{
		if (this != &c)
		{
			this->_real = c._real;
			this->_image = c._image;
		}
		return *this;
	}


	~Plural()
	{
		//cout << "析构函数" << endl;
	}
	bool operator >(const Plural& c);
	bool operator <(const Plural& c);
	bool operator ==(const Plural& c);
	Plural operator +(const Plural& c);
	Plural operator -(const Plural& c);
	Plural operator *(const Plural& c);
	Plural operator /(const Plural& c);
private:
	double  _real;
	double  _image;
};


//bool比较大小
bool Plural::operator >(const Plural& c)//this指针为隐指针,不可自己以参数方式传入,但可以直接使用;也可省略不显示写出
{
	return sqrt((this->_real)*(this->_real) + (this->_image)*(this->_image)) > sqrt((c._real)*(c._real) + (c._image)*(c._image));
}
bool Plural::operator <(const Plural& c)
{
	return !(*this>c);
}
bool Plural::operator ==(const Plural& c)
{
	return sqrt((this->_real)*(this->_real) + (this->_image)*(this->_image)) == sqrt((c._real)*(c._real) + (c._image)*(c._image));
}


//复数的四则运算
Plural Plural::operator+(const Plural &c)//相加
{
	Plural tmp;
	tmp._real = this->_real + c._real;
	tmp._image = this->_image + c._image;
	return tmp;
}
Plural Plural::operator-(const Plural &c)//相减
{
	Plural tmp;
	tmp._real = this->_real - c._real;
	tmp._image = this->_image - c._image;
	return tmp;
}
Plural  Plural:: operator*(const Plural &c)// 复数的乘除较为复杂,因为相乘时存在i^2=-1此类的情况以及相除存在通分情况
{
	Plural tmp;//(a+bi)(c+di)=(ac-bd)+(bc+ad)i;
	tmp._real = (this->_real*c._real) - (this->_image*c._image);
	tmp._image = (this->_image*c._real) + (this->_real*c._image);
	return tmp;
}
Plural  Plural:: operator/(const Plural &c)
{
	Plural tmp;//(a+bi)/(c+di)=x+yi,x=(ac+bd)/(c*c+d*d),y=(bc-ad)/(c*c+d*d);
	tmp._real = ((this->_real*c._real) + (this->_image*c._image)) / (c._real*c._real + c._image*c._image);
	tmp._image = ((this->_image*c._real) - (this->_real*c._image)) / (c._real*c._real + c._image*c._image);
	return tmp;
}

//测试用例
void  Test1()
{
	Plural a, b(3, 5);
	a.Display();
	b.Display();
	cout << "Ret=" << (a < b) << endl;
}


//主函数
int  main()
{
	Test1();
	return 0;
}


注:复数类的相关运算对于初识C++中类和对象相关概念的初学者来说,是一个不错的典型范例,分析其由类初始的创建以及成员函数的具体定义实现,可以很好地锻炼新手的代码水平和逻辑构思能力。

你可能感兴趣的:(类和对象,复数类,初识类和对象,复数类的四则运算)