---》:原则上复数是不能比较大小的,此处主要是练习运算符重载才写的复数比较大小:
#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() //析构函数
{}
void Display() //显示函数
{
cout<<_real<<"+"<<_image<<"i"<<endl;
}
Complex operator+(Complex c) //重载+函数
{
_real = _real + c._real;
_image = _image + c._image;
return *this;
}
bool operator>(const Complex& c)const //重载>函数
{
if(_real>c._real)
return true;
else if(_real==c._real)
{
if(_image>c._image)
{
return true;
}
else
return false;
}
else
return false;
}
bool operator<(const Complex& c)const //重载<函数
{
if(_real<c._real)
return true;
else if(_real==c._real)
{
if(_image<c._image)
{
return true;
}
else
return false;
}
else
return false;
}
bool operator ==(const Complex& c)const //重载==函数
{
if((_real == c._real)&&(_image == c._image))
return true;
else
return false;
}
bool operator!=(const Complex& c) //重载!=函数
{
return !(*this == c);
}
Complex& operator=(const Complex& c)
{
_real = c._real;
_image = c._image;
return *this;
}
Complex operator++() //前置++
{
_real++;
return *this;
}
Complex operator++(int) //后置++
{
Complex temp = *this;
_real++;
return temp;
}
Complex operator--() //前置--
{
_real--;
return *this;
}
Complex operator--(int) //后置--
{
Complex temp = *this;
_real--;
return temp;
}
Complex operator+=(double x) //重载+=函数
{
_real += x;
return *this;
}
protected:
double _real;
double _image;
};
void Test1() // +(加)、++(后置)、++(前置)
{
Complex c1(1,2);
Complex c2(2,3);
Complex c3(3,5);
Complex c4,c5,c6;
c4=(c1+c2);
c4.Display();
c5=c2++;
c5.Display();
c6=++c3;
c6.Display();
}
void Test2()// >(大于)、<(小于)、+=(加等)、==(等于)
{
Complex c1(2,2);
Complex c2(4,3);
Complex c3(3,5);
bool c = true;
c=c1<c2;
cout<<c<<endl;
c=c1>c3;
cout<<c<<endl;
Complex c4(2,2);
Complex c5;
c5=c4+=3;
c5.Display();
Complex c6(2,2);
c=c1==c6;
cout<<c<<endl;
}
int main()
{
Test1();
Test2();
return 0;
}