复数类运算符重载

#include<iostream>
using namespace std;
class Complex
{
private:
	double real;
	double imag;
public:
	Complex(double real_m = 0,double imag_m = 0)
	{
		real = real_m;
		imag = imag_m;
	}
	Complex operator+(Complex &co);//重载+号,实现复数相加
	Complex operator-(Complex &co);//重载-号,实现复数相减
	Complex operator*(Complex &co);//重载×号,实现复数相乘
	Complex operator/(Complex &co);//重载/号,实现复数相除
	friend Complex operator+(int i,Complex &co); //重载+号,实现实数与复数相加
	friend Complex operator+(Complex co,int i); //重载+号,实现复数与实数相加
	Complex operator++();//重载自增运算符,实现复数前置自增
	Complex operator++(int);//重载自增运算符,实现复数后置自增
	friend ostream & operator<<(ostream & output , Complex &co);//重载cout,实现直接输出复数类
	friend istream & operator>>(istream & input , Complex &co);
};
istream & operator>>(istream & input , Complex &co)
{
	input>>co.real>>co.imag;
	return input;
}
Complex Complex::operator++(int)
{
	++real;
	return *this;
}
Complex Complex::operator++()
{
	++real;
	return *this;
}
Complex operator+(Complex co,int i)
{
	Complex c;
	c.real = i+co.real;
	c.imag = co.imag;
	return c;
}
Complex operator+(int i,Complex &co)
{
	Complex c;
	c.real = i+co.real;
	c.imag = co.imag;
	return c;
}
ostream & operator<<(ostream & output , Complex &co)
{
	if(co.imag>0)
	{
		output<<"(  "<<co.real<<"+"<<co.imag<<"i  )";
	}else if(co.imag==0)
	{
		output<<"(  "<<co.real<<"  )";
	}else
	{
		output<<"("<<co.real<<co.imag<<"i)";
	}
	return output;
}
Complex Complex::operator+(Complex &co)
{
	Complex c;
	c.real = real + co.real;
	c.imag = imag + co.imag;
	return c;
}
Complex Complex::operator-(Complex &co)
{
	Complex c;
	c.real = real - co.real;
	c.imag = imag - co.imag;
	return c;
}
Complex Complex::operator*(Complex &co)
{
	Complex c;
	c.real = real*co.real-imag*co.imag;
	c.imag = imag*co.real-real*co.imag;
	return c;
}
Complex Complex::operator/(Complex &co)
{
	Complex c;
	c.real = (double)((real*co.real+imag*co.imag)/(co.real*co.real+co.imag*co.imag));
	c.imag = (double)((imag*co.real-real*co.imag)/(co.real*co.real+co.imag*co.imag));
	return c;
}
int main()
{
	Complex c1(1,3);
	Complex c2(2,3);
	Complex c3;
	c3 = c1+c2;
	cout<<c1<<" + "<<c2<<" = "<<c3<<endl;
	c3 = c1-c2;
	cout<<c1<<" - "<<c2<<" = "<<c3<<endl;
	c3 = c1*c2;
	cout<<c1<<" * "<<c2<<" = "<<c3<<endl;
	c3 = c1/c2;
	cout<<c1<<" / "<<c2<<" = "<<c3<<endl;
	c3 = 3+c1;
	cout<<" 3 "<<" + "<<c1<<" = "<<c3<<endl;
	c3 = c1 + 3;
	cout<<c1<<" + "<<" 3 "<<" = "<<c3<<endl;
	cout<<c1<<"前置自增后为:";cout<<++c1<<endl;
	cout<<c1<<"后置自增后为:";cout<<c1++<<endl;
	cin>>c1;
	return 0;
}

  

posted @ 2020-10-10 18:48  骑码的佳俊  阅读(380)  评论(0编辑  收藏  举报