#include <iostream>
using namespace std;
class complex{
double real,image;
public:
complex(double a=0,double b=0){
real=a;image=b;
}
complex operator-(complex c){
return complex(real-c.real,image-c.image);
}
complex operator-=(complex c){
real=real-c.real;image=image-c.image;
return *this;
}
complex operator*=(complex c){
complex t;
t.real=real*c.real-image*c.image;
t.image=real*c.image+c.real*image;
real=t.real;image=t.image;
return t;
}
complex operator/=(complex c){
complex t;
double d=c.real*c.real+c.image*c.image;
t.real=(real*c.real+image*c.image)/d;
t.image=(image*c.real-real*c.image)/d;
real=t.real;image=t.image;
return t;
}
complex operator++(int){
cout<<real++<<"+"<<image++<<"i"<<endl;
cout<<real<<"+"<<image<<"i"<<endl;
}
complex operator++(){
cout<<++real<<"+"<<++image<<"i"<<endl;
cout<<real<<"+"<<image<<"i"<<endl;
}
void print(){
if(image>=0)cout<<real<<"+"<<image<<"i"<<endl;
else cout<<real<<image<<"i"<<endl;
}
};
int main(){
complex c1(2.1,4.3),c2(4.5,6.6),c;//自动调用含两个参数或默认的构造函数c=c1-c2
c.print();
c2-=c1;//c2.operator-=(c1)
c2.print();
c1*=c2;//c1.operator*=(c2)
c1.print();
c/=c2;//c1.operator/=(c2)
c.print();
c2++;
++c2;
}
重载函数使用
最新推荐文章于 2024-07-12 10:56:01 发布