复数的运算规则在下面代码中有具体说明
#include <iostream>
#define EXP 0.0000000000
using namespace std;
class Complex
{
public:
// 1.完成四个默认成员函数
Complex(double real = 8.0, double image = -6.0)//构造函数
{
_real=real;
_image=image;
cout<<"Complex(double real,double image)"<<endl;
}
Complex(const Complex& d)//拷贝构造函数
{
cout<<"Complex(const Complex& d)"<<endl;
_image = d._image;
_real = d._real ;
}
~Complex()//析构函数
{
cout<<"~Complex()"<<endl;
}
Complex& operator=(const Complex& d)//赋值运算符重载
{
cout<<"Complex& operator=(const Complex& d)"<<endl;
if(this != &d)
{
_real = d._real;
_image = d._image;
}
return *this;
}
void Display()const//打印复数
{
if(_image>EXP)
{
cout<<_real<<"+"<<_image<<"i"<<endl;
}
else if(_image<EXP)
{
cout<<_real<<_image<<"i"<<endl;
}
}
// 2.比较运算符
//复数只有当虚部为0时,即_image=0时,才可以比较大小,
//这时比较的是实部即_real的大小
bool operator>(const Complex& d)
{
if(this->_image==0 && d._image==0)
return this->_real>d._real;
else
cout<<"error";
}
bool operator<(const Complex& d)
{
if(this->_image==0 && d._image==0)
return this->_real<d._real;
else
cout<<"error";
}
bool operator==(const Complex& d)
{
return this->_real==d._real&&this->_image==d._image;
}
bool operator!=(const Complex& d)
{
return this->_real != d._real
|| this->_image != d._image;
}
// 3.前置后置++和+/+=的实现
Complex& operator++()//前置++
{
this->_real+=1;
return *this;
}
Complex operator++(int)//后置++
{
Complex tmp(*this);
this->_real+=1;
return tmp;
}
Complex& operator+=(Complex& d)
{
this->_real=(this->_real + d._real);
this->_image=(this->_image + d._image) ;
return *this;
}
Complex operator+(const Complex& d)
{
Complex ret;
ret._real = (this->_real + d._real);
ret._image = (this->_image + d._image);
return ret;
}
protected:
double _real;
double _image;
};