#include <iostream>
using namespace std;
class Complex
{
public:
Complex(const double _real, const double _image);
Complex(const Complex& complex);
~Complex();
Complex& operator=(const Complex& c);
Complex operator+(const Complex& c);
Complex operator-(const Complex& c);
Complex operator*(const Complex& c);
Complex operator/(const Complex& c);
Complex& operator+=(const Complex& c);
Complex& operator-=(const Complex& c);
Complex& operator*=(const Complex& c);
Complex& operator/=(const Complex& c);
void display();
private:
double _real;
double _image;
};
//构造函数
Complex::Complex(const double real=0.0, const double image=0.0)
{
_real = real;
_image = image;
}
// 拷贝构造函数
Complex::Complex(const Complex& c)
:_real(c._real)
, _image(c._image)
{}
//析构函数
Complex::~Complex()
{}
// 赋值重载
Complex& Complex::operator=(const Complex& c)
{
if (this != &c)
{
_real = c._real;
_image = c._image;
}
return *this;
}
// +操作符重载
Complex Complex::operator+(const Complex& c)
{
Complex c1;
c1._real = _real + c._real;
c1._image = _image + c._image;
return c1;
}
// -操作符重载
Complex Complex::operator-(const Complex& c)
{
Complex c1;
c1._real = _real - c._real;
c1._image = _image - c._image;
return c1;
}
// *操作符重载(a+bi)(c+di)=ac-bd+(ad+bc)i
//a:_real; b:_image; c:c._real; d:c._image;
Complex Complex::operator*(const Complex& c)
{
Complex c1;
c1._real = c._real*_real - c._image*_image;
c1._image = c._real*_image + c._image*_real;
return c1;
}
// /操作符重载(a+bi)/(c+di)=1/(c*c+d*d)*(ac+bd+(bc-ad)i)
//a:_real; b:_image; c:c._real; d:c._image;
Complex Complex::operator/(const Complex& c)
{
Complex c1;
c1._real = (c._real*_real + c._image*_image) / (c._real*c._real + c._image*c._image);
c1._image = (_image*c._real - _real*c._image) / (c._real*c._real + c._image*c._image);
return c1;
}
// +=操作符重载
Complex& Complex::operator+=(const Complex& c)
{
this->_real += c._real;
this->_image += c._image;
return *this;
}
// -=操作符重载
Complex& Complex::operator-=(const Complex& c)
{
this->_real -= c._real;
this->_image -= c._image;
return *this;
}
// *=操作符重载
Complex& Complex::operator*=(const Complex& c)
{
*this = *this * c;
return *this;
}
// /=操作符重载
Complex& Complex::operator/=(const Complex& c)
{
*this = *this / c;
return *this;
}
//打印
void Complex::display()
{
cout << "(" << _real << "," << _image<<")"<< endl;
}
void FunTest()
{
Complex c1(1.0,2.0);
Complex c2(3.0,4.0);
Complex c3 = c1 + c2;
cout << "c3:";
c3.display();
Complex c4 = c1 - c2;
cout << "c4:";
c4.display();
Complex c5 = c1 * c2;
cout << "c5:";
c5.display();
Complex c6 = c2 / c1;
cout << "c6:";
c6.display();
Complex c7;
c7 += c2;
cout << "c7:";
c7.display();
Complex c8;
c8 -= c2;
cout << "c8:";
c8.display();
Complex c9(3,5);
c9 *= c1;
cout << "c9:";
c9.display();
Complex c10(1,2);
c10 /= c2;
cout << "c10:";
c10.display();
}
int main()
{
FunTest();
system("pause");
return 0;
}