#include <iostream>
using namespace std;
class complex{
private:
double real,image;
public:
complex(double r=0,double i=0){//两个参数的构造函数
real=r;image=i;
}
complex(const complex &c){//复制构造函数
real=c.real;
image=c.image;
}
~complex(){//析构函数
cout<<"*******xigou*******"<<endl;
}
void print(){
if(image>=0) cout<<real<<"+"<<image<<"i"<<endl;
else cout<<real<<image<<"i"<<endl;
}
friend complex operator-(complex &,const complex &);//重载+
friend complex operator-=(complex &,const complex &);//重载-=
friend complex operator*=(complex &,const complex &);//重载*=
friend complex operator/=(complex &,const complex &);//重载/=
friend complex operator++(complex &);//重载前置++
friend complex operator++(complex &,int);//重载后置++
};
complex operator-( complex &c1,const complex &c2){//重载+
complex t(c1.real-c2.real,c1.image-c2.image);
c1.real=t.real;c1.image=t.image;
return c1;
}
complex operator-=(complex &c1,const complex &c2){//重载-=
c1.real=c1.real-c2.real,c1.image=c1.image-c2.image;
return c1;
}
complex operator*=(complex &c1,const complex &c2){//重载*=
complex t(c1.real*c2.real-c1.image*c2.image,c1.real*c2.image+c2.real*c1.image);
c1.real=t.real;c1.image=t.image;
return c1;
}
complex operator/=(complex &c1,const complex &c2){//重载/=
complex t((c1.real*c2.real+c1.image*c2.image)/(c2.real*c2.real+c2.image*c2.image),
(c1.real*c2.image+c2.real*c1.image)/(c2.real*c2.real+c2.image*c2.image));
c1.real=t.real;c1.image=t.image;
return c1;
}
complex operator++(complex &s){//重载前置++
return complex(++s.real,++s.image);
}
complex operator++(complex &c1,int){//重载后置++
return complex(c1.real++,c1.image++);
}
int main(){
complex c1(1.0,1.0),c2(2.0,2.0),c3(3.0,3.0),c;
cout<<"c1:";c1.print();
cout<<"c2:";c2.print();
cout<<"c3:";c3.print();
cout<<"c:";c.print();
c=c1-c2;c.print();
c-=c1;c.print();
c1*=c2;c1.print();
c1/=c2;c1.print();
c3++;c3.print();
++c3;c3.print();
return 0;
}
运算符重载作业
最新推荐文章于 2024-06-19 15:56:33 发布