#include
class Complex //复数类
{
double real; double image ;
public :
Complex (double x=0.0,double y=0.0)
{
real=x; image=y;
}
~Complex() // 析构函数
{
cout<<"("<<real<<","<<image<<")被析构"<<endl;
}
Complex (const Complex &com1);//拷贝构造函数
void print ();
friend Complex operator +(const Complex &c1,const Complex &c2); //声明友元函数
friend Complex operator -(const Complex &c1,const Complex &c2);
friend Complex operator *(const Complex &c1,const Complex &c2);
friend Complex operator /(const Complex &c1,const Complex &c2);
friend Complex operator -(const Complex &c1); //数值取反
friend ostream &operator<<( ostream &os,const Complex &c1); //重载运算符<<
};
Complex::Complex (const Complex &com1) //定义拷贝构造函数
{
real=com1.real ;image=com1.image ;
cout<<"Copy"<<endl;
}
Complex fun (Complex com2)
{
Complex com3(com2);
return com3;
}
void Complex ::print () //输出函数
{
if (!real)
{
cout<<image<<"i"<<endl;
}
else
{
if (image<0)
cout<<real<<image<<"i"<<endl;
else
cout<<real<<"+"<<image<<"i"<<endl;
}
}
Complex operator +(const Complex &c1,const Complex &c2) //定义友元函数 加法
{
Complex temp(c1.real +c2.real ,c1.image +c2.image );
return temp;
}
Complex operator -(const Complex &c1,const Complex &c2) //减法
{
Complex temp(c1.real -c2.real ,c1.image -c2.image );
return temp;
}
Complex operator *(const Complex &c1,const Complex &c2) //乘法
{
Complex temp (c1.real *c2.real -c1.image *c2.image,c1.real *c2.image+c1.image *c2.real);
return temp;
}
Complex operator /(const Complex &c1,const Complex &c2) //除法
{
Complex temp ((c1.real *c2.real +c1.image *c2.image)/(c2.real *c2.real+c2.image+c2.image),(c1.real *c2.image-c1.image *c2.real)/(c2.real *c2.real+c2.image+c2.image));
return temp;
}
Complex operator -(const Complex &c1) //取反
{
Complex temp(-c1.real ,-c1.image );
return temp;
}
ostream &operator<<( ostream &cout,const Complex &c1) //重载<<运算符
{
cout<<"("<<c1.real <<","<<c1.image <<")"<<endl;
return cout;
}
int main()
{
Complex c1(1,1),c2(2,2),c3,c4,c5,c6,c7,co1;
c3=c1+c2;
c3.print ();
c4=c2-c1;
c4.print ();
c5=c1*c2;
c5.print ();
c6=c2/c1;
c6.print ();
c7=-c1;
c7.print ();
co1=c1;
co1=fun(c1);
co1.print ();
cout<<c1;
return 0;
}