#include <iostream>
#include<stdlib.h>
using namespace std;
class Complex
{
public:
Complex(double real, double image);
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);
bool operator == (const Complex &c);
void print(Complex &c);
private:
double _real;
double _image;
};
Complex::Complex(double r = 0.0, double i = 0.0)
{
_real = r;
_image = i;
}
//两复数相加
Complex Complex::operator + (const Complex &c)
{
Complex tmp;
tmp._real = _real + c._image;
tmp._image = _image + c._image;
return tmp;
}
//两复数相减
Complex Complex::operator - (const Complex &c)
{
Complex tmp;
tmp._image = _image - c._image;
tmp._real = _real - c._real;
return tmp;
}
//两复数相乘
Complex Complex::operator*(const Complex &c)
{
Complex tmp;
tmp._image = _image* c._image;
tmp._real = _real* c._real;
return tmp;
}
//两复数相除
Complex Complex::operator / (const Complex &c)
{
Complex tmp;
tmp._real = _real / c._real;
tmp._image = _image / c._image;
return tmp;
}
//加等
Complex Complex::operator += (const Complex &c)
{
this->_real += c._real;
this->_image += c._image;
return *this;
}
//减等
Complex Complex::operator -= (const Complex &c)
{
this->_image -= c._image;
this->_real -= c._real;
return *this;
}
//乘等
Complex Complex::operator *= (const Complex &c)
{
this->_image *= c._image;
this->_real *= c._real;
return *this;
}
Complex Complex::operator /= (const Complex &c)
{
this->_image /= c._image;
this->_real /= c._real;
return *this;
}
bool Complex::operator == (const Complex &c)
{
return (this->_image == c._image) && (this->_real == c._real);
}
void Complex::print(Complex &c)
{
cout << c._real << "+"<< c._image <<"i" << endl;
}
void Test1()
{
Complex c1(1.0, 2.0), c2(2.0, 1.0);
Complex c3 = c1 *= c2;
cout << (c1 == c2) << endl;
c1.print(c1);
c3.print(c3);
}
int main()
{
Test1();
return 0;
}
复数类
最新推荐文章于 2021-04-16 16:53:55 发布