运算符重载综合实例
- 格式:doc
- 大小:62.00 KB
- 文档页数:3
运算符重载综合实例
class MyComplex{ double Real;double Imag;
public:
//构造函数
MyComplex(const double &r=0.0,const double &i=0.0){Real=r;Imag=i;cout<<"Constructor !"< 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--"< MyComplex operator+(const MyComplex &c1, const MyComplex &c2){ MyComplex result(c1.Real+c2.Real,c1.Imag+c2.Imag); cout<<"operator+"< return result; } int operator==(const MyComplex &c1, const MyComplex &c2){ cout<<"operator=="< return (c1.Real==c2.Real)&& (c1.Imag==c2.Imag); } MyComplex::MyComplex(const MyComplex &c){ Real=c.Real;Imag=c.Imag;cout<<"Copy Constructor !"< MyComplex MyComplex::operator=(const MyComplex &c){ Real=c.Real;Imag=c.Imag; cout<<"operator="< cout<<"operatorunary-"< MyComplex MyComplex::operator++(int){MyComplex result(Real++,Imag++); cout<<"operatorpostfix++"< MyComplex MyComplex::operator-(const MyComplex &c){ Real-=c.Real; Imag-=c.Imag;cout<<"operatorbinary-"< Real+=c.Real; Imag+=c.Imag; cout<<"operator+="< 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< cout< cout< cout< cout< } Constructor ! Constructor ! Constructor ! Copy Constructor ! Copy Constructor ! Constructor ! operatorpostfix++ Copy Constructor ! operator+= Copy Constructor ! operatorunary- Copy Constructor ! Constructor ! operatorpostfix-- Copy Constructor ! Constructor !