Tải bản đầy đủ - 0 (trang)
Chapter 14.  Overloaded Operations and Conversions

Chapter 14.  Overloaded Operations and Conversions

Tải bản đầy đủ - 0trang

Thesefacilitiesallowprogrammerstowritearichsetofmixedtypeexpressions.

C++letsusredefinethemeaningoftheoperatorswhenapplied

toobjectsofclasstype.Italsoletsusdefineconversion

operationsforclasstypes.Class-typeconversionsareusedlike

thebuilt-inconversionstoimplicitlyconvertanobjectofone

typetoanothertypewhenneeded.

Operatoroverloadingallowstheprogrammertodefineversions

oftheoperatorsforoperandsofclasstype.Chapter13covered

theimportanceoftheassignmentoperatorandshowedhowto

definetheassignmentoperator.Wefirstusedoverloaded

operatorsinChapter1,whenourprogramsusedtheshift

operators(>>and<<)forinputandoutputandtheaddition

operator(+)toaddtwoSales_items.We'llfinallyseeinthis

chapterhowtodefinetheseoverloadedoperators.

Throughoperatoroverloading,wecanredefinemostofthe

operatorsfromChapter5toworkonobjectsofclasstype.

Judicioususeofoperatoroverloadingcanmakeclasstypesas

intuitivetouseasthebuilt-intypes.Forexample,thestandard

librarydefinesseveraloverloadedoperatorsforthecontainer

classes.Theseclassesdefinethesubscriptoperatortoaccess

dataelementsand*and->todereferencecontaineriterators.

Thefactthattheselibrarytypeshavethesameoperators

makesusingthemsimilartousingbuilt-inarraysandpointers.

Allowingprogramstouseexpressionsratherthannamed

functionscanmaketheprogramsmucheasiertowriteand

read.Asanexample,compare

cout<<"Thesumof"<
<<"is"<


tothemoreverbosecodethatwouldbenecessaryifIOused

namedfunctions:



//hypotheticalexpressionifIOusednamedfunctions

cout.print("Thesumof").print(v1).

print("and").print(v2).print("is").

print(v1+v2).print("\n").flush();



14.1.DefininganOverloadedOperator

Overloadedoperatorsarefunctionswithspecialnames:the

keywordoperatorfollowedbythesymbolfortheoperatorbeing

defined.Likeanyotherfunction,anoverloadedoperatorhasa

returntypeandaparameterlist.



Sales_itemoperator+(constSales_item&,constSales_item&)



declarestheadditionoperatorthatcanbeusedto"add"two

Sales_itemobjectsandyieldsacopyofaSales_itemobject.

Withtheexceptionofthefunction-calloperator,anoverloaded

operatorhasthesamenumberofparameters(includingthe

implicitthispointerformemberfunctions)astheoperatorhas

operands.Thefunction-calloperatortakesanynumberof

operands.



OverloadedOperatorNames

Table14.1onthenextpageliststheoperatorsthatmaybe

overloaded.Thosethatmaynotbeoverloadedarelistedin

Table14.2.

Table14.1.OverloadableOperators

+



-



*



/



%



^



&



|



~



!



,



=



<



>



<=



>=



++



--



<<



>>



==



!=



&&



||



+=



-=



/=



%=



^=



&=



|=



*=



<<=



>>=



[]



()



->



->*



new



new[]



delete



delete[]



Table14.2.OperatorsThatCannotBeOverloaded

::



.*



.



?:



Newoperatorsmaynotbecreatedbyconcatenatingotherlegal

symbols.Forexample,itwouldbeillegaltoattempttodefine

anoperator**toprovideexponentiation.Overloadingnewand

deleteisdescribedinChapter18(p.753).



OverloadedOperatorsMustHaveanOperandof

ClassType

Themeaningofanoperatorforthebuilt-intypesmaynotbe

changed.Forexample,thebuilt-inintegeradditionoperation

cannotberedefined:

//error:cannotredefinebuilt-inoperatorforints

intoperator+(int,int);



Normayadditionaloperatorsbedefinedforthebuilt-indata

types.Forexample,anoperator+takingtwooperandsofarray



typescannotbedefined.

Anoverloadedoperatormusthaveatleastoneoperandof

classorenumeration(Section2.7,p.62)type.Thisrule

enforcestherequirementthatanoverloadedoperator

maynotredefinethemeaningoftheoperatorswhen

appliedtoobjectsofbuilt-intype.



PrecedenceandAssociativityAreFixed

Theprecedence(Section5.10.1,p.168),associativity,or

numberofoperandsofanoperatorcannotbechanged.

Regardlessofthetypeoftheoperandsandregardlessofthe

definitionofwhattheoperationsdo,thisexpression

x==y+z;



alwaysbindstheargumentsyandztooperator+andusesthat

resultastheright-handoperandtooperator==.

Foursymbols(+,-,*,and&)serveasbothunaryandbinary

operators.Eitherorbothoftheseoperatorscanbeoverloaded.

Whichoperatorisbeingdefinediscontrolledbythenumberof

operands.Defaultargumentsforoverloadedoperatorsare

illegal,exceptforoperator(),thefunction-calloperator.



Short-CiruitEvaluationIsNotPreserved



Overloadedoperatorsmakenoguaranteesabouttheorderin

whichoperandsareevaluated.Inparticular,theoperandevaluationguaranteesofthebuilt-inlogicalAND,logicalOR

(Section5.2,p.152),andcomma(Section5.9,p.168)

operatorsarenotpreserved.Bothoperandstoanoverloaded

versionof&&or||arealwaysevaluated.Theorderinwhich

thoseoperandsareevaluatedisnotstipulated.Theorderin

whichtheoperandstothecommaareevaluatedisalsonot

defined.Forthisreason,itisusuallyabadideatooverload&&,

||,orthecommaoperator.



ClassMemberversusNonmember

Mostoverloadedoperatorsmaybedefinedasordinary

nonmemberfunctionsorasclassmemberfunctions.

Overloadedfunctionsthataremembersofaclassmay

appeartohaveonelessparameterthanthenumberof

operands.Operatorsthatarememberfunctionshavean

implicitthisparameterthatisboundtothefirstoperand.



Anoverloadedunaryoperatorhasno(explicit)parameterifitis

amemberfunctionandoneparameterifitisanonmember

function.Similarly,anoverloadedbinaryoperatorwouldhave

oneparameterwhendefinedasamemberandtwoparameters

whendefinedasanonmemberfunction.

TheSales_itemclassoffersagoodexampleofmemberand

nonmemberbinaryoperators.Weknowthattheclasshasan

additionoperator.Becauseithasanadditionoperator,weought



todefineacompound-assignment(+=)operatoraswell.This

operatorwilladdthevalueofoneSales_itemobjectintoanother.

Ordinarilywedefinethearithmeticandrelationaloperatorsas

nonmemberfunctionsandwedefineassignmentoperatorsas

members:



//memberbinaryoperator:left-handoperandboundtoimplicitthispointer

Sales_item&Sales_item::operator+=(constSales_item&);

//nonmemberbinaryoperator:mustdeclareaparameterforeachoperand

Sales_itemoperator+(constSales_item&,constSales_item&)



Bothadditionandcompoundassignmentarebinaryoperators,

yetthesefunctionsdefineadifferentnumberofparameters.

Thereasonforthediscrepancyisthethispointer.

Whenanoperatorisamemberfunction,thispointstothelefthandoperand.Thus,thenonmemberoperator+definestwo

parameters,bothreferencestoconstSales_itemobjects.Even

thoughcompoundassignmentisabinaryoperator,themember

compound-assignmentoperatortakesonlyone(explicit)

parameter.Whentheoperatorisused,apointertothelefthandoperandisautomaticallyboundtothisandtheright-hand

operandisboundtothefunction'ssoleparameter.

Itisalsoworthnotingthatcompoundassignmentreturnsa

referenceandtheadditionoperatorreturnsaSales_itemobject.

Thisdifferencematchesthereturntypesoftheseoperators

whenappliedtoarithmetictypes:Additionyieldsanrvalueand

compoundassignmentreturnsareferencetotheleft-hand

operand.



OperatorOverloadingandFriendship



Whenoperatorsaredefinedasnonmemberfunctions,they

oftenmustbemadefriends(Section12.5,p.465)ofthe

class(es)onwhichtheyoperate.We'llseelaterinthischapter

tworeasonswhyoperatorsmightbedefinedasnonmembers.

Insuchcases,theoperatoroftenneedsaccesstotheprivate

partsoftheclass.

OurSales_itemclassisagainagoodexampleofwhysome

operatorsneedtobefriends.Itdefinesonememberoperator

andhasthreenonmemberoperators.Thosenonmember

operators,whichneedaccesstotheprivatedatamembers,are

declaredasfriends:



classSales_item{

friendstd::istream&operator>>

(std::istream&,Sales_item&);

friendstd::ostream&operator<<

(std::ostream&,constSales_item&);

public:

Sales_item&operator+=(constSales_item&);

};

Sales_itemoperator+(constSales_item&,constSales_it



Thattheinputandoutputoperatorsneedaccesstotheprivate

datashouldnotbesurprising.Afterall,theyreadandwrite

thosemembers.Ontheotherhand,thereisnoneedtomake

theadditionoperatorafriend.Itcanbeimplementedusingthe

publicmemberoperator+=.



UsingOverloadedOperators

Wecanuseanoverloadedoperatorinthesamewaythatwe'd

usetheoperatoronoperandsofbuilt-intype.Assumingitem1

anditem2areSales_itemobjects,wemightprinttheirsuminthe



samewaythatwe'dprintthesumoftwoints:

cout<


Thisexpressionimplicitlycallstheoperator+thatwedefinedfor

Sales_items.

Wealsocancallanoverloadedoperatorfunctioninthesame

waythatwecallanordinaryfunction:Wenamethefunction

andpassanappropriatenumberofargumentsofthe

appropriatetype:

//equivalentdirectcalltononmemberoperatorfunction

cout<


Thiscallhasthesameeffectastheexpressionthataddeditem1

anditem2.

Wecallamemberoperatorfunctionthesamewaywecallany

othermemberfunction:Wenameanobjectonwhichtorunthe

functionandthenusethedotorarrowoperatortofetchthe

functionwewishtocallpassingtherequirednumberandtype

ofarguments.Inthecaseofabinarymemberoperator

function,wemustpassasingleoperand:



item1+=item2;//expressionbased"call"

item1.operator+=(item2);//equivalentcalltomemberop



Eachofthesestatementsaddsthevalueofitem2intoitem1.In

thefirstcase,weimplicitlycalltheoverloadedoperatorfunction

usingexpressionsyntax.Inthesecond,wecallthemember

operatorfunctionontheobjectitem1.



ExercisesSection14.1

Inwhatwaysdoesanoverloadedoperatordifferfromabuilt-in

Exercise

operator?Inwhatwaysareoverloadedoperatorsthesameas

14.1:

thebuilt-inoperators?



Exercise Writedeclarationsfortheoverloadedinput,output,additionand

14.2: compound-assignmentoperatorsforSales_item.



Explainthefollowingprogram,assumingthattheSales_item

constructorthattakesastringisnotexplicit.Explainwhat

happensifthatconstructorisexplicit.

Exercise

14.3: stringnull_book="9-999-99999-9";

Sales_itemitem(cin);

item+=null_book;



Boththestringandvectortypesdefineanoverloaded==thatcan

beusedtocompareobjectsofthosetypes.Identifywhich

versionof==isappliedineachofthefollowingexpressions:

Exercise strings;vectorsvec1,svec2;

14.4: "cobble"=="stone"

svec1[0]==svec2[0];

svec1==svec2



14.1.1.OverloadedOperatorDesign

Whendesigningaclasstherearesomeusefulrulesofthumbto

keepinmindwhendecidingwhich,ifany,overloadedoperators

toprovide.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 14.  Overloaded Operations and Conversions

Tải bản đầy đủ ngay(0 tr)

×