Bootstrap

C++中运算符重载实现复数的加减乘除

#include "stdafx.h"
#include "Complex.h"
#include <iostream>
using namespace std;

//输入运算符重载
istream & operator >>(istream &in,Complex &c)
{
	in>>c.real>>c.imag;
	return in;
}
//输出运算符重载
ostream & operator <<(ostream &out,Complex &c)
{
	if(c.imag>0)
		out<<c.real<<"+"<<c.imag<<"i"<<endl;
	else if(c.real==0)
		out<<c.imag<<"i"<<endl;
	else if(c.imag==0)
		out<<c.real<<endl;
	else out<<c.real<<c.imag<<"i"<<endl;
	return out;
}
Complex::Complex()
{real=0;imag=0;}
Complex::Complex(double r,double i)
{
	real=r;
	imag=i;
}
//实现复数+复数
Complex Complex::operator+(Complex &c1)
{
	Complex c;
	c.real=real+c1.real;
	c.imag=imag+c1.imag;
	return c;
}
//复数+实数
Complex Complex::operator+(double r)
{
	Complex c;
	c.real=real+r;
	c.imag=imag;
	return c;
}
//实数+复数
Complex operator+(double r,Complex &c1)
{
	Complex c;
	c.real=r+c1.real;
	c.imag=c1.imag;
	return c;
}
//-复数   对复数取反
Complex Complex::operator-(void)
{
	Complex c;
	c.real=-real;
	c.imag=-imag;
	return c;
}
//复数-复数
Complex Complex::operator-(Complex &c1)
{
	Complex c;
	c.real=real-c1.real;
	c.imag=imag-c1.imag;
	return c;
}
//复数-实数
Complex Complex::operator-(double r)
{
	Complex c;
	c.real=real-r;
	c.imag=imag;
	return c;
}
//实数-复数
Complex operator-(double r,Complex &c1)
{
	Complex c;
	c.real=r-c1.real;
	c.imag=-c1.imag;
	return c;
}
//自增++
Complex Complex::operator++()//++前置
{
	Complex c;
	c.real=++real;
	c.imag=++imag;
	return c;
}
Complex Complex::operator++(int)//++后置
{
	Complex temp(*this);
	real++;
	imag++;
	return temp;
}

//自减--
Complex Complex::operator--()//--前置
{
	Complex c;
	c.real=--real;
	c.imag=--imag;
	return c;
}
Complex Complex::operator--(int)//--后置
{
	Complex temp(*this);
	real--;
	imag--;
	return temp;
}

//复数*复数
Complex Complex::operator*(Complex &c1)
{
	Complex c;
	c.real=real*c1.real-imag*c1.imag;
	c.imag=real*c1.imag+imag*c1.real;
	return c;
}

//复数*实数
Complex Complex::operator*(double r)
{
	Complex c;
	c.real=real*r;
	c.imag=imag*r;
	return c;
}

//实数*复数
Complex operator*(double r,Complex &c1)
{
	Complex c;
	c.real=r*c1.real;
	c.imag=r*c1.imag;
	return c;
}

//复数除复数
Complex Complex::operator/(Complex &c1)
{
	Complex c;
	c.real=(real*c1.real+imag*c1.imag)/(c1.real*c1.real+c1.imag*c1.imag);
	c.imag=(imag*c1.real-real*c1.imag)/(c1.real*c1.real+c1.imag*c1.imag);
	return c;
}
//复数除实数
Complex Complex::operator/(double r)
{
	if(r)//判断被除数是否为0
	{
		Complex c;
		c.real=real/r;
		c.imag=imag/r;
		return c;
	}
	else cout<<"Arithmetic Exception"<<endl;
}
//实数除复数
Complex operator/(double r,Complex &c1)
{
	Complex c;
	c.real=r*c1.real/(c1.real*c1.real+c1.imag*c1.imag);
	c.imag=-r*c1.imag/(c1.real*c1.real+c1.imag*c1.imag);
	return c;
}

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;