问题描述:

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


#include<iostream>
using  namespace std;


class Plural
{
public:
void  Display()
{
cout << "Real->:" << _real;
cout << " Image->:" << _p_w_picpath << endl;
}

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


Plural(Plural& a)//拷贝构造函数,注意引用符,若为值传递则可能会引发无穷递归
{
_p_w_picpath = a._p_w_picpath;
_real = a._real;
}


Plural& operator =(const Plural& c)//返回值可实现链式访问,不改变原有值,则加const修饰符
{
if (this != &c)
{
this->_real = c._real;
this->_p_w_picpath = c._p_w_picpath;
}
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  _p_w_picpath;
};


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


//复数的四则运算
Plural Plural::operator+(const Plural &c)//相加
{
Plural tmp;
tmp._real = this->_real + c._real;
tmp._p_w_picpath = this->_p_w_picpath + c._p_w_picpath;
return tmp;
}
Plural Plural::operator-(const Plural &c)//相减
{
Plural tmp;
tmp._real = this->_real - c._real;
tmp._p_w_picpath = this->_p_w_picpath - c._p_w_picpath;
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->_p_w_picpath*c._p_w_picpath);
tmp._p_w_picpath = (this->_p_w_picpath*c._real) + (this->_real*c._p_w_picpath);
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->_p_w_picpath*c._p_w_picpath)) / (c._real*c._real + c._p_w_picpath*c._p_w_picpath);
tmp._p_w_picpath = ((this->_p_w_picpath*c._real) - (this->_real*c._p_w_picpath)) / (c._real*c._real + c._p_w_picpath*c._p_w_picpath);
return tmp;
}

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


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


注:初识类与对象,希望各位大牛不吝赐教。