C++實現一個複數類
阿新 • • 發佈:2019-02-05
#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;
}