用友元运算符重载函数进行复数运算

#include
using namespace std;
class Complex
{
	public:
		Complex(double r=0.0,double i=0.0);
		void print();
		friend Complex operator+(Complex &a,Complex & b);//声明运算符+ 重载函数 
		friend Complex operator-(Complex &a,Complex & b);//声明运算符- 重载函数  
		friend Complex operator*(Complex &a,Complex & b);//声明运算符* 重载函数 
		friend Complex operator/(Complex &a,Complex & b);//声明运算符/ 重载函数 
	private:
		double real;//复数实部 
		double imag;//复数虚部 
};
Complex::Complex(double r,double i)  //构造函数
{
	real=r;
	imag=i;
}
Complex operator+(Complex &a,Complex & b)//定义运算符+重载函数 
{
	Complex temp;
	temp.real=a.real+b.real;
	temp.imag=a.imag+b.imag;
	return temp;
}
Complex operator-(Complex &a,Complex & b)//定义运算符-重载函数 
{
	Complex temp;
	temp.real=a.real-b.real;
	temp.imag=a.imag-b.imag;
	return temp;
}
Complex operator*(Complex &a,Complex & b)//定义运算符*重载函数 
{
	Complex temp;
	temp.real=a.real*b.real-a.imag*b.imag;
	temp.imag=a.real*b.imag+a.imag*b.real;
	return temp;
}
Complex operator/(Complex &a,Complex & b)//定义运算符/重载函数 
{
	Complex temp;
	double t;
	t=1/(b.real*b.real+b.imag*b.imag);
	temp.real=(a.real*b.real+a.imag*b.imag)*t;
	temp.imag=(-b.imag*a.real+a.imag*b.real)*t;
	return temp;
}
void Complex::print()//显示输出复数函数  
{
	cout<<real;
	if(imag>0) 
	cout<<"+";
	if(imag!=0)
	cout<<imag<<"i"<<endl;
}
int main()
{
	Complex A1(2.3,4.6),A2(3.6,2.8),A3,A4,A5,A6;
	A3=A1+A2;
	A4=A1-A2;
	A5=A1*A2;
	A6=A1/A2;
	A1.print();
	A2.print();
	A3.print();
	A4.print();
	A5.print();
	A6.print();
	return 0;
}

我快服了,我自己高中毕业还没一年,我的复数就忘光了,我快哭了。。。
复数除法注意实部和虚部

你可能感兴趣的:(用友元运算符重载函数进行复数运算)