运算符重载综合实例

  • 格式:doc
  • 大小:62.00 KB
  • 文档页数:3

下载文档原格式

  / 3
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

运算符重载综合实例

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 !