复数类的运算有加减乘除四个,下面我们来逐步分析这几个运算。
一·加法运算
设z1=a+bi,z2=c+di是任意两个复数,则它们的和是 (a+bi)+(c+di)=(a+c)+(b+d)i;
此处需要注意的是返回值的类型为复数complex。
具体代码实现如下:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double r,double i);
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;
}
//两复数相乘(a+bi)(c+di)=(ac-bd)+(bc+ad)i
Complex Complex::operator*(const Complex &c)
{
Complex tmp;
tmp._real = _real*c._image - _image*c._real;
tmp._image = _image*c._real + _real*c._image;
return tmp;
}
//两复数相除(ac+bd)/(c^2+d^2)+(bc-ad)/(c^2+d^2)i
Complex Complex :: operator/(const Complex &c)
{
Complex tmp;
double deno = c._real*c._real + c._image*c._image;//有理化后的分母denominator
tmp._real = deno*((_real*c._real) + (_image*c._image));
tmp._image = deno*((_image*c._real) - (_real*c._image));
return tmp;
}
Complex Complex::operator+=(const Complex &c)
{
Complex tmp;
tmp._real += c._real;
tmp._image += c._image;
return tmp;
}
Complex Complex::operator-=(const Complex &c)
{
Complex tmp;
tmp._real -= c._real;
tmp._image -= c._image;
return tmp;
}
bool Complex::operator==(const Complex &c)
{
return(_real == c._real) && (_image == c._image);
}
void Complex::print(Complex &c)
{
cout << c._real << "+ " << c._image << "i" << endl;
}
int main()
{
Complex *c = NULL;
Complex c1(9.0, 5.0);
Complex c2(7.0, 6.0);
Complex ret;
cout << (c1 == c2) << endl;//输出c1,c2是否相等
c->print(c1);//输出c1+c2
c->print(c2);
cout << "c1+c2=";
ret = c1 + c2;
c->print(ret);
system("pause");
return 0;
}