【C++】复数类的实现

复数类的运算有加减乘除四个,下面我们来逐步分析这几个运算。

一·加法运算

z1=a+bi,z2=c+di是任意两个复数,则它们的和是 (a+bi)+(c+di)=(a+c)+(b+d)i;

此处需要注意的是返回值的类型为复数complex。


二.减法运算

z1=a+bi,z2=c+di是任意两个复数, 则它们的差是(a+bi)-(c+di)=(a-c)+(b-d)i.

同样这里的返回值类型也应该为复数complex。


三.乘法运算

z1=a+bi,z2=c+di(a、b、c、d∈R)是任意两个复数,那么它们的积(a+bi)(c+di)=(ac-bd)+(bc+ad)i.

同样这里的返回值类型也应该为复数complex。



四.除法运算

满足(c+di)(x+yi)=(a+bi)的复数x+yi(x,y∈R)叫复数a+bi除以复数c+di的商
可以把 除法当成乘法做,分子分母上同时乘上分母的共轭.运算结果为:
(ac+bd)/(c^2+d^2)+(bc-ad)/(c^2+d^2)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;
}



你可能感兴趣的:(C++复数类运算的实现,复数类的实现)