《操作符重载》PPT课件.ppt

《操作符重载》PPT课件.ppt

ID:52086155

大小:388.34 KB

页数:35页

时间:2020-03-31

《操作符重载》PPT课件.ppt_第1页
《操作符重载》PPT课件.ppt_第2页
《操作符重载》PPT课件.ppt_第3页
《操作符重载》PPT课件.ppt_第4页
《操作符重载》PPT课件.ppt_第5页
资源描述:

《《操作符重载》PPT课件.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、第七章操作符重载苏劲松2012年本章内容操作符重载的需要性作为成员函数重载作为全局(友元)函数重载一些特殊操作符的重载操作符重载的需要性C++本身没有提供复数类型,可定义一个类来实现:classComplex//复数类定义{public:Complex(doubler=0.0,doublei=0.0){real=r;imag=i;}voiddisplay()const{cout<

2、dd:classComplex{public:Complexadd(constComplex&x)const{Complextemp;temp.real=real+x.real;temp.imag=imag+x.imag;returntemp;}……};……Complexa(1.0,2.0),b(3.0,4.0),c;c=a.add(b);方案二:定义一个全局函数:classComplex//复数类定义{......friendComplexcomplex_add(constComplex&x1,constComplex&x2);};C

3、omplexcomplex_add(constComplex&x1,constComplex&x2){Complextemp;temp.real=x1.real+x2.real;temp.imag=x1.imag+x2.imag;returntemp;}Complexa(1.0,2.0),b(3.0,4.0),c;c=complex_add(a,b);两种实现均不符合数学上的习惯c=a+b;C++允许对已有的操作符进行重载,使得它们能对自定义类型(类)的对象进行操作。操作符可以以两种方式重载:以成员函数形式重载classComplex{

4、public:Complexoperator+(constComplex&x)const{Complextemp;temp.real=real+x.real;temp.imag=imag+x.imag;returntemp;}......};……Complexa(1.0,2.0),b(3.0,4.0),c;c=a+b;以带有类、结构、枚举或者它们的引用类型参数的全局函数形式重载classComplex{......friendComplexoperator+(constComplex&c1,constComplex&c2);};Comp

5、lexoperator+(constComplex&c1,constComplex&c2){Complextemp;temp.real=c1.real+c2.real;temp.imag=c1.imag+c2.imag;returntemp;}……Complexa(1.0,2.0),b(3.0,4.0),c;c=a+b;操作符重载的基本原则只能重载C++语言中已有的操作符,不可臆造新的操作符。可以重载C++中除下列操作符外的所有操作符:“.”,“.*”,“?:”,“::”,“sizeof”重载不改变原操作符的优先级和结合性。重载不能改变

6、操作数个数。尽量遵循已有操作符的语义(不是必需的)。作为成员函数重载操作符双目操作符重载定义格式class<类名>{......<返回值类型>operator#(<类型>);//#代表操作符};<返回值类型><类名>::operator#(<类型><参数>){......}使用格式<类名>a;<类名>b;a#b或a.operator#(b)例、实现复数的“等于”和“不等于”操作。classComplex{doublereal,imag;public:......booloperator==(constComplex&x)const{re

7、turn(real==x.real)&&(imag==x.imag);}booloperator!=(constComplex&x)const{return!(*this==x);}};Complexc1,c2;......if(c1==c2)//或if(c1!=c2)单目操作符重载定义格式class<类名>{......<返回值类型>operator#();};<返回值类型><类名>::operator#(){......}使用格式<类名>a;#a或a.operator#()例:实现复数的取负操作classComplex{......

8、public:Complexoperator-()const{Complextemp;temp.real=-real;temp.imag=-imag;returntemp;}};......Complexa

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。