C++計算機語言教學課件c++-lect06operatoroverloading_第1頁
C++計算機語言教學課件c++-lect06operatoroverloading_第2頁
C++計算機語言教學課件c++-lect06operatoroverloading_第3頁
C++計算機語言教學課件c++-lect06operatoroverloading_第4頁
C++計算機語言教學課件c++-lect06operatoroverloading_第5頁
已閱讀5頁,還剩39頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Chapter5-C++OperatorOverloadingOutline5.1 Introduction5.2 FundamentalsofOperatorOverloading5.3 RestrictionsonOperatorOverloading5.4 OperatorFunctionsasClassMembersvs.asfriendFunctions5.5 OverloadingStream-InsertionandStream-ExtractionOperators5.6 OverloadingUnaryOperators 5.7 OverloadingBinaryOperators5.8 CaseStudy:AnArrayClass5.9 ConvertingbetweenTypes5.10 Overloading++and--

ObjectivesInthischapter,youwilllearn:Tounderstandhowtoredefine(overload)operatorstoworkwithnewtypes.Tounderstandhowtoconvertobjectsfromoneclasstoanotherclass.Tolearnwhento,andwhennotto,overloadoperators.Tostudyseveralinterestingclassesthatuseoverloadedoperators.TocreateanArrayclass.

4.1Introduction(1)運算符重載是對已有的運算符賦予多重含義,使同一個運算符作用于不同類型的數(shù)據(jù)時,產(chǎn)生不同類型的行為。C++允許同一運算符具有多種不同運算功能的機制。(2)為什么需要運算符重載:C++中預定義了許多運算符,能夠滿足用戶的一般應用要求,但是其運算的對象應是基本數(shù)據(jù)類型,而不適用于用戶自定義數(shù)據(jù)類型(如類),這可以使用運算符重載。(3)明智地使用操作符重載可以使類類型的使用像內置類型一樣直觀(4)操作符的實質是函數(shù)重載。4.1IntroductionOperatoroverloading

Usetraditionaloperatorswithuser-definedobjectsStraightforwardandnaturalwaytoextendC++Requiresgreatcare

Whenoverloadingismisused,programsbecomedifficulttounderstand

classpoint {public: point(intxx=0,intyy=0){x=xx;y=yy;}

intget_x();

intget_y(); //...private:

intx;

inty;};pointp1(1,1),p2(3,3),實現(xiàn)“p1+p2”則需要編寫程序來說明“+”如何作用于point對象(p1,p2),即p1的私有成員x,y與p2的私有成員x,y分別相加這一功能。4.2FundamentalsofOperatorOverloadingUseoperatoroverloadingtoimprovereadabilityAvoidexcessiveorinconsistentusageFormatWritefunctiondefinitionasnormal(重載函數(shù)跟普通函數(shù)一樣,具有返回類型和形參表)Functionnameiskeywordoperatorfollowedbythesymbolfortheoperatorbeingoverloaded.

operator+wouldbeusedtooverloadtheadditionoperator(+).4.2FundamentalsofOperatorOverloadingAssignmentoperator(=)maybeusedwitheveryclasswithoutexplicitoverloadingmemberwiseassignment(不需專門定義,默認存在,逐一復制數(shù)據(jù)成員)class

MyClass{

public:...

MyClass&operator=(const

MyClass&rhs);...}

MyClass&MyClass::operator=(const

MyClass&rhs){...return*this;}

MyClassa,b,c;...a=b=c;//Sameasb.operator=(a);4.3RestrictionsonOperatorOverloading

MostofC++’soperatorscanbeoverloaded有四個符號(+,-,*和&)既可作一元操作符又可作二元操作符,可以同時定義一元和二元操作符重載操作符不能改變原操作符的優(yōu)先級、結合性或操作數(shù)目重載操作符必須具有至少一個自定義類類型類型的操作數(shù),也就是說重載操作符不能重新定義用于內置類型對象的操作符的含義,比如不能重載”+”號操作符用于兩個整數(shù)相加。ExampleAnoverloadingfortheoperator“+”forthisclass

classpoint {public: point(int

xx=0,int

yy=0){x=xx;y=yy;}

int

get_x();

int

get_y();pointoperator+(constpoint&rpt);//...private:

intx;

int

y;};pointpoint::operator+(constpoint&rpt){

int

tempx=x+rpt.get_x();

int

tempy=y+rpt.get_y();pointtemp(tempx,tempy);returntemp;}ExampleAnoverloadingfortheoperator“+”forthisclass

//**include“point.h”;include<iostream>main(){pointa(15,20),b(5,13);pointtestpoint;

testpoint=a+b;

}ClasspracticeWriteanoverloadingfortheoperator“*=”forthisclass

classpoint {public: point(intxx=0,intyy=0){x=xx;y=yy;}

intget_x();

intget_y(); //...private:

intx;

inty;};pointp1(1,1),p2(3,3),實現(xiàn)“p1*=p2”,即p1的私有成員x,y與p2的私有成員x,y分別相乘,并將結果分別賦于p1的私有成員。ClasspracticeWriteanoverloadingfortheoperator“*=”

classpoint {public: point(int

xx=0,int

yy=0){x=xx;y=yy;}

int

get_x();

int

get_y();point&operator*=(constpoint&rpt);//...private:

intx;

int

y;};point&point::operator*=(constpoint&rpt){x=x*rpt.get_x();y=y*rpt.get_y();return*this;}4.4OperatorFunctionsasClassMembersvs.asfriendFunctionsOperatorfunctionsCanbememberornon-memberfunctionsOverloadingtheassignmentoperatorsi.e:(),[],->,=Operatormustbeamemberfunction

4.4OperatorFunctionsasClassMembersvs.asfriendFunctionsOperatorfunctionsasmemberfunctionsLeftmostoperandmustbeanobject(orreferencetoanobject)oftheclassIfleftoperandofadifferenttype(與定義的class不一致),operatorfunctionmustbeanon-memberfunctionAnon-memberoperatorfunctionmustbeafriendifprivateorprotectedmembersofthatclassareaccesseddirectly如果需要訪問類的私有或者保護對象4.4OperatorFunctionsasClassMembersvs.asfriendFunctionsNon-memberoverloadedoperatorfunctionsEnabletheoperatortobecommutative(可交換的),becausetheleftmostoperandcanbeanothertype.

HugeIntegerbigInteger1;longintnumber;bigInteger1=number+bigInteger1; orbigInteger1=biginteger1+number;4.4OperatorFunctionsasClassMembersvs.asfriendFunctionsFriendfunctionMemberFunctiona+boperator+(a,b)a.operator+(b)a++operator++(a,0)a.operator++(0)-aoperator-(a)a.operator-()類成員的操作符函數(shù)與其等價的友元函數(shù):4.4OperatorFunctionsasClassMembersvs.asfriendFunctions友元運算符函數(shù)無this指針,因而在函數(shù)體內必須通過對象名來使用private成員數(shù)據(jù);一般將一元運算符函數(shù)重載為成員運算符函數(shù)。強調:與賦值相關的運算符必須重載成成員函數(shù)。一般將二元運算符重載為友元運算符函數(shù),以免出現(xiàn)使用錯誤。因為時常需要操作數(shù)可交換“=”、“()”、“[]”和“->”不能重載為友元。4.5OverloadingStream-InsertionandStream-ExtractionOperators

Overloaded<<

and

>>operatorsMusthaveleftoperandoftypesostream&,istream&respectivelyItmustbe

anon-memberfunction(leftoperandnotanobjectoftheclass)Itmustbeafriendfunctionifitaccessesprivatedatamembers注意:在本課程學習的OperatorOverloading中,通過non-memberfunction來定義operator,就是指用friendfunction來實現(xiàn)fig18_03.cpp(1of3)語法:friend<函數(shù)類型>operator<運算符>(形參表){函數(shù)體;}fig18_03.cpp(2of3)fig18_03.cpp(3of3)Enterphonenumberintheform(123)456-7890:(800)555-1212Thephonenumberenteredwas:(800)555-12124.6OverloadingUnaryOperatorsOverloadingunaryoperatorsAvoid

friendfunctionsandfriendclassesunlessabsolutelynecessary.Useoffriendsviolatestheencapsulationofaclass.Asamemberfunction:classString{

public:

booloperator!()const;

...

};<函數(shù)類型>operator<運算符>(形參表){函數(shù)體;}4.7OverloadingBinaryOperatorsOverloadedbinaryoperatorsNon-staticmemberfunction,oneargumentNon-memberfunction(friend),twoarguments

classString{

public:

constString&operator+=(constString&);

...

};//endclassString

y+=z;

equivalenttoy.operator+=(

z

);4.7OverloadingBinaryOperatorsExampleclassString{friend

constString&operator+=(String&,constString&);...};//endclassString

y+=z;equivalent

to

operator+=(

y,

z

);語法:friend<函數(shù)類型>operator<運算符>(形參表){函數(shù)體;}4.8CaseStudy:AnArrayclassImplementanArrayclasswith

RangecheckingArrayassignmentArraysthatknowtheirsizeOutputting/inputtingentirearrayswith<<and>>Arraycomparisonswith==and!=array1.h(1of2)array1.h(2of2)array1.cpp(1of6)array1.cpp(2of6)array1.cpp(3of6)array1.cpp(3of6)array1.cpp(4of6)array1.cpp(5of6)array1.cpp(6of6)fig18_04.cpp(1of4)fig18_04.cpp(2of4)fig18_04.cpp(3of4)fig18_04.cpp(4of4)Arrayoutput(1of1)#ofarraysinstantiated=0#ofarraysinstantiated=2

Sizeofarrayintegers1is7Arrayafterinitialization:0000000

Sizeofarrayintegers2is10Arrayafterinitialization:0000000000Input17integers:1234567891011121314151617Afterinput,thearrayscontain:integers1:1234567integers2:891011121314151617

Evaluating:integers1!=integers2Theyarenotequal

Sizeofarrayintegers3is7Arrayafterinitialization:1234567Arrayoutput(2of2)Assigningintegers2tointegers1:integers1:891011121314151617integers2:891011121314151617Evaluating:integers1==integers2Theyareequal

integers1[5]is13Assigning1000tointegers1[5]integers1:89101112100014151617

Attempttoassign1000tointegers1[15]Assertionfailed:0<=subscript&&subscript<size,fileArray1.cpp,line95abnormalprogramtermination4.9ConvertingbetweenTypesCastoperatorConvertobjectsintobuilt-intypesorotherobjectsConversionoperatormustbeanon-static

memberfunction.Cannotbeafriendfunction形參表必須為空不能指定返回類型,但是必須顯式返回一個指定類型的值轉換函數(shù)采用如下通用形式:operatortype();type表

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論