运算符重载综合实例
class MyComplex{ double Real;double Imag;
public:
//构造函数
MyComplex(const double &r=0.0,const double &i=0.0){Real=r;Imag=i;cout<<"Constructor !"<<endl;} //拷贝构造函数
MyComplex(const MyComplex &);
double GetReal(){return Real;}
double GetImag(){return Imag;}
//赋值运算符重载为成员函数
MyComplex operator=(const MyComplex &c);
//负数运算符重载为成员函数
MyComplex operator-();
//后缀加1,成员函数
MyComplex operator++(int);
//后缀减1,外部函数
friend MyComplex operator--(MyComplex &,int);
//加法,外部函数
friend MyComplex operator+(const MyComplex &, const MyComplex &);
//减法,成员函数
MyComplex operator-(const MyComplex &);
//加赋值,成员函数
MyComplex operator+=(const MyComplex &);
//比较,外部函数和
friend int operator==(const MyComplex &, const MyComplex &);
};
MyComplex operator--( MyComplex &c,int){MyComplex result(c.Real--,c.Imag--);
cout<<"operatorpostfix--"<<endl;return result;}
MyComplex operator+(const MyComplex &c1, const MyComplex &c2){
MyComplex result(c1.Real+c2.Real,c1.Imag+c2.Imag);
cout<<"operator+"<<endl;
return result;
}
int operator==(const MyComplex &c1, const MyComplex &c2){
cout<<"operator=="<<endl;
return (c1.Real==c2.Real)&&
(c1.Imag==c2.Imag);
}
MyComplex::MyComplex(const MyComplex &c){
Real=c.Real;Imag=c.Imag;cout<<"Copy Constructor !"<<endl;}
MyComplex MyComplex::operator=(const MyComplex &c){
Real=c.Real;Imag=c.Imag; cout<<"operator="<<endl;return *this;} MyComplex MyComplex::operator-(){Real=-Real;Imag=-Imag;
cout<<"operatorunary-"<<endl;return *this;}
MyComplex MyComplex::operator++(int){MyComplex result(Real++,Imag++);
cout<<"operatorpostfix++"<<endl; return result;}
MyComplex MyComplex::operator-(const MyComplex &c){
Real-=c.Real; Imag-=c.Imag;cout<<"operatorbinary-"<<endl;return *this;} MyComplex MyComplex::operator+=(const MyComplex &c){
Real+=c.Real; Imag+=c.Imag; cout<<"operator+="<<endl; return *this;}
void main(){
MyComplex a(10,20),b(11,21),e,*p;
MyComplex c(a);
MyComplex d=b;
d+=c++;
e=((a+b)-(c--))+(-d);
p=new MyComplex(21,22);
if(!p) return;
e+=(d==(*p));
if(p) delete p;
cout<<a.GetReal()<<"+j"<<a.GetImag()<<endl;
cout<<b.GetReal()<<"+j"<<b.GetImag()<<endl;
cout<<c.GetReal()<<"+j"<<c.GetImag()<<endl;
cout<<d.GetReal()<<"+j"<<d.GetImag()<<endl;
cout<<e.GetReal()<<"+j"<<e.GetImag()<<endl;
}
Constructor !
Constructor !
Constructor !
Copy Constructor !
Copy Constructor !
Constructor !
operatorpostfix++
Copy Constructor !
operator+=
Copy Constructor !
operatorunary-
Copy Constructor !
Constructor !
operatorpostfix--
Copy Constructor !
Constructor !
operator+
Copy Constructor ! operatorbinary- Copy Constructor ! Constructor ! operator+
Copy Constructor ! operator=
Copy Constructor ! Constructor ! operator== Constructor ! operator+=
Copy Constructor ! 10+j20
11+j21
10+j20
-21+j-41
-11+j-21。