*烟台大学计算机学院学生
*All right reserved.
*文件名称*烟台大学计算机学院学生
*All right reserved.
*文件名称:项目一运算符重载《和》的体验
*作者:杨飞
*完成日期:2014年4月11日
*版本号:v1.0
*对任务及求解方法的描述部分:项目一运算符重载《和》的体验
*我的程序:*
#include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r,double i)
{
real=r;
imag=i;
}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
friend istream & operator >>(istream &,Complex&);
friend ostream & operator <<(ostream &,Complex&);
Complex operator-();
private:
double real;
double imag;
};
//复数相加: (a+bi)+(c+di)=(a+c)+(b+d)i.
Complex Complex::operator+(Complex &c2)
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
//复数相减:(a+bi)-(c+di)=(a-c)+(b-d)i.
Complex Complex::operator-(Complex &c2)
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
//复数相乘:(a+bi)(c+di)=(ac-bd)+(bc+ad)i.
Complex Complex::operator*(Complex &c2)
{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;
}
//复数相除:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +(bc-ad)/(c^2+d^2)i
Complex Complex::operator/(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;
}
int main()
{
Complex c1,c2,c3;
cout<<"请输入两个数代表实部和虚部"<<endl;
cin>>c1;
cout<<"请输入两个数代表实部和虚部"<<endl;
cin>>c2;
cout<<"c1=";
cout<<c1;
cout<<"c2=";
cout<<c2;
c3=c1+c2;
cout<<"c1+c2=";
cout<<c3;
c3=c1-c2;
cout<<"c1-c2=";
cout<<c3;
c3=c1*c2;
cout<<"c1*c2=";
cout<<c3;
c3=c1/c2;
cout<<"c1/c2=";
cout<<c3;
cout<<"-c2=";
c2=-c2;
cout<<c2;
return 0;
}
istream & operator >>(istream &putin,Complex&c)
{
putin>>c.real>>c.imag;
return putin;
}
ostream & operator <<(ostream &output,Complex&c)
{
output<<"("<<c.real;
if(c.imag>0)
output<<"+";
output<<c.imag<<"i"<<")"<<endl;
return output;
}
Complex Complex::operator-()
{ Complex c;
c.real=-real;
c.imag=-imag;
return c;
}
运行结果:
心得体会:呵呵!!!