#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()
{
}
Complex&
operator=(Complex& c)
{
if (
this!=&c)
{
this->_real = c._real;
this->_image = c._image;
}
return *
this;
}
bool operator==(
const Complex& c)
{
if (
this->_image !=
0 || c._image !=
0)
{
cout <<
"虚数不能比较大小" << endl;
return false;
}
return (
this->_image == c._image) && (
this->_real==c._real);
}
bool operator!=(
const Complex& c)
{
if (
this->_image !=
0 || c._image !=
0)
{
cout <<
"虚数不能比较大小" << endl;
return false;
}
return !(
this->_image == c._image) && (
this->_real == c._real);
}
bool operator>(
const Complex& c)
{
if (
this->_image !=
0 || c._image !=
0)
{
cout <<
"虚数不能比较大小" << endl;
return false;
}
else
{
if (_real > c._real)
return true;
else
return false;
}
}
bool operator>=(
const Complex& c)
{
if (
this->_image !=
0 || c._image !=
0)
{
cout <<
"虚数不能比较大小" << endl;
return false;
}
return (*
this == c || *
this > c);
}
bool operator<(
const Complex& c)
{
if (
this->_image !=
0 || c._image !=
0)
{
cout <<
"虚数不能比较大小" << endl;
return false;
}
return !(*
this >= c);
}
bool operator<=(
const Complex& c)
{
if (
this->_image !=
0 || c._image !=
0)
{
cout <<
"虚数不能比较大小" << endl;
return false;
}
return !(*
this>c);
}
Complex
operator+(
const Complex& c)
{
Complex sum;
sum._real = _real + c._real;
sum._image = _image + c._image;
return sum;
}
Complex&
operator+=(
const Complex& c)
{
_real =
this->_real + c._real;
_image =
this->_image + c._image;
return *
this;
}
Complex
operator-(
const Complex& c)
{
Complex sub;
sub._real = _real - c._real;
sub._image = _image - c._image;
return sub;
}
Complex&
operator-=(
const Complex& c)
{
_real =
this->_real - c._real;
_image =
this->_image - c._image;
return *
this;
}
Complex
operator*(
const Complex& c)
{
Complex mul;
mul._real = (
this->_real * c._real) - (
this->_image *c._image);
mul._image = (
this->_real * c._real) +(
this->_image *c._image);
return mul;
}
Complex
operator/(
const Complex& c)
{
Complex div;
div._real = ((
this->_real*c._real) + (
this->_image*c._image)) / (c._real*c._real + c._image*c._image);
div._image = ((
this->_image*c._real) - (
this->_real*c._image)) / (c._real*c._real + c._image*c._image);
return div;
}
Complex&
operator++()
{
this->_real++;
this->_image++;
return *
this;
}
Complex
operator++(
int)
{
Complex tmp(*
this);
this->_real++;
this->_image++;
return tmp;
}
void Display()
{
cout << _real <<
"+" << _image <<
"i" << endl;
}
private:
double _real;
double _image;
};
void test()
{
Complex c1(
2,
1);
c1.Display();
Complex c2(
3,
1);
c2.Display();
bool ret = (c1 <c2);
cout << ret << endl;
Complex c3 = c1 - c2;
c3.Display();
Complex c4 = c1 + c2;
c4.Display();
c1-=c2;
c1.Display();
Complex c5 = c1 /c2;
c5.Display();
c1++;
c1.Display();
++c1;
c1.Display();
}
int main()
{
test();
system(
"pause");
return 0;
}
结果如下: