/*
*copyright(c) 2015,烟台大学计算机学院
*All rights reserved。
*文件名称:第九周(运算符重载)
*作者:王忠
*完成日期:2015.5.13
*版本号:v1.0
*
*问题描述:定义Complex类中的<<和>>运算符的重载,实现输入和输出,
*输入描述:
*程序输出:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r; imag=i;}
Complex operator+(const Complex &c2);
Complex operator-(const Complex &c2);
Complex operator*(const Complex &c2);
Complex operator/(const Complex &c2);
friend Complex operator-(Complex &c2);
void display();
friend ostream& operator <<(ostream& output,const Complex& c);
friend istream& operator >>(istream& input,Complex& c);
private:
double real;
double imag;
};
//下面定义成员函数
Complex Complex::operator+(const Complex &c2)
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
Complex Complex::operator-(const Complex &c2)
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
Complex Complex::operator*(const Complex &c2)
{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;
}
Complex Complex::operator/(const Complex &c2)
{
Complex c;
c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
void Complex::display()
{
cout<<real;
if(imag>0)
cout<<'+'<<imag<<'i'<<endl;
else
cout<<imag<<'i'<<endl;
}
Complex operator-(Complex &c2)
{
Complex c;
return (c-c2);
}
ostream& operator <<(ostream& output,const Complex& c)
{
output<<'('<<c.real;
if(c.imag>=0)
output<<'+';
output<<c.imag<<"i)";
return output;
}
istream& operator >>(istream& input,Complex& c)
{
int a,b;
char sign,i;
do
{
cout<<"input (a+bi or a-bi)\n";
input>>a>>sign>>b>>i;
}while(!(sign=='+'||sign=='-')&&i=='i');
c.real=a;
c.imag=(sign=='+')?b:-b;
return input;
}
//下面定义用于测试的main()函数
int main()
{
Complex c1,c2,c3;
cout<<"c1: "<<endl;;
cin>>c1;
cout<<"c2: "<<endl;
cin>>c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
c3=-c3;
c3.display();
return 0;
}
又成功一个,耶