Tải bản đầy đủ - 0 (trang)
Chapter 11. Operator Overloading; String and Array Objects

Chapter 11. Operator Overloading; String and Array Objects

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

Chapter11.OperatorOverloading;String

andArrayObjects

Thewholedifferencebetweenconstructionand

creationisexactlythis:thatathingconstructedcan

onlybelovedafteritisconstructed;butathing

createdislovedbeforeitexists.

GilbertKeithChesterton

Thedieiscast.

JuliusCaesar

Ourdoctorwouldneverreallyoperateunlessitwas

necessary.Hewasjustthatway.Ifhedidn'tneed

themoney,hewouldn'tlayahandonyou.

HerbShriner

OBJECTIVES

Inthischapteryouwilllearn:

Whatoperatoroverloadingisandhowitmakesprograms

morereadableandprogrammingmoreconvenient.

Toredefine(overload)operatorstoworkwithobjectsof

user-definedclasses.

Thedifferencesbetweenoverloadingunaryandbinary

operators.



Toconvertobjectsfromoneclasstoanotherclass.

Whento,andwhennotto,overloadoperators.

TocreatePhoneNumber,Array,StringandDateclassesthat

demonstrateoperatoroverloading.

Touseoverloadedoperatorsandothermemberfunctionsof

standardlibraryclassstring.

Tousekeywordexplicittopreventthecompilerfromusing

single-argumentconstructorstoperformimplicit

conversions.



[Page572]

Outline

11.1Introduction

11.2FundamentalsofOperatorOverloading

11.3RestrictionsonOperatorOverloading

11.4OperatorFunctionsasClassMembersvs.GlobalFunctions

11.5OverloadingStreamInsertionandStreamExtraction

Operators

11.6OverloadingUnaryOperators

11.7OverloadingBinaryOperators

11.8CaseStudy:ArrayClass

11.9ConvertingbetweenTypes



11.10CaseStudy:StringClass

11.11Overloading++and-11.12CaseStudy:ADateClass

11.13StandardLibraryClassstring

11.14explicitConstructors

11.15Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises



[Page572(continued)]



11.1.Introduction

Chapters910introducedthebasicsofC++classes.Services

wereobtainedfromobjectsbysendingmessages(intheform

ofmember-functioncalls)totheobjects.Thisfunctioncall

notationiscumbersomeforcertainkindsofclasses(suchas

mathematicalclasses).Also,manycommonmanipulationsare

performedwithoperators(e.g.,inputandoutput).Wecanuse

C++'srichsetofbuilt-inoperatorstospecifycommonobject

manipulations.ThischaptershowshowtoenableC++'s

operatorstoworkwithobjectsaprocesscalledoperator

overloading.ItisstraightforwardandnaturaltoextendC++

withthesenewcapabilities,butitmustbedonecautiously.

OneexampleofanoverloadedoperatorbuiltintoC++is<<,

whichisusedbothasthestreaminsertionoperatorandasthe

bitwiseleft-shiftoperator(whichisdiscussedinChapter22,

Bits,Characters,Stringsandstructs).Similarly,>>isalso

overloaded;itisusedbothasthestreamextractionoperator

andasthebitwiseright-shiftoperator.[Note:Thebitwiseleftshiftandbitwiseright-shiftoperatorsarediscussedindetailin

Chapter22.]BothoftheseoperatorsareoverloadedintheC++

StandardLibrary.

Althoughoperatoroverloadingsoundslikeanexoticcapability,

mostprogrammersimplicitlyuseoverloadedoperators

regularly.Forexample,theC++languageitselfoverloadsthe

additionoperator(+)andthesubtractionoperator(-).These

operatorsperformdifferently,dependingontheircontextin

integerarithmetic,floating-pointarithmeticandpointer

arithmetic.

C++enablestheprogrammertooverloadmostoperatorstobe

sensitivetothecontextinwhichtheyareusedthecompiler

generatestheappropriatecodebasedonthecontext(in



particular,thetypesoftheoperands).Someoperatorsare

overloadedfrequently,especiallytheassignmentoperatorand

variousarithmeticoperatorssuchas+and-.Thejobs

performedbyoverloadedoperatorscanalsobeperformedby

explicitfunctioncalls,butoperatornotationisoftenclearerand

morefamiliartoprogrammers.



[Page573]

Wediscusswhento,andwhennotto,useoperatoroverloading.

Weimplementuser-definedclassesPhoneNumber,Array,Stringand

Datetodemonstratehowtooverloadoperators,includingthe

streaminsertion,streamextraction,assignment,equality,

relational,subscript,logicalnegation,parenthesesand

incrementoperators.Thechapterendswithanexampleof

C++'sStandardLibraryclassstring,whichprovidesmany

overloadedoperatorsthataresimilartoourStringclassthatwe

presentearlierinthechapter.Intheexercises,weaskyouto

implementseveralclasseswithoverloadedoperators.The

exercisesalsouseclassesComplex(forcomplexnumbers)and

HugeInt(forintegerslargerthanacomputercanrepresentwith

typelong)todemonstrateoverloadedarithmeticoperators+and

-andaskyoutoenhancethoseclassesbyoverloadingother

arithmeticoperators.







[Page573(continued)]



11.2.FundamentalsofOperatorOverloading

C++programmingisatype-sensitiveandtype-focused

process.Programmerscanusefundamentaltypesandcan

definenewtypes.Thefundamentaltypescanbeusedwith

C++'srichcollectionofoperators.Operatorsprovide

programmerswithaconcisenotationforexpressing

manipulationsofobjectsoffundamentaltypes.

Programmerscanuseoperatorswithuser-definedtypesaswell.

AlthoughC++doesnotallownewoperatorstobecreated,it

doesallowmostexistingoperatorstobeoverloadedsothat,

whentheseoperatorsareusedwithobjects,theoperatorshave

meaningappropriatetothoseobjects.Thisisapowerful

capability.



SoftwareEngineeringObservation11.1

OperatoroverloadingcontributestoC++'s

extensibilityoneofthelanguage'smostappealing

attributes.



GoodProgrammingPractice11.1

Useoperatoroverloadingwhenitmakesaprogram

clearerthanaccomplishingthesameoperationswith

functioncalls.



GoodProgrammingPractice11.2

Overloadedoperatorsshouldmimicthefunctionalityof

theirbuilt-incounterpartsforexample,the+operator

shouldbeoverloadedtoperformaddition,not

subtraction.Avoidexcessiveorinconsistentuseof

operatoroverloading,asthiscanmakeaprogramcryptic

anddifficulttoread.



Anoperatorisoverloadedbywritinganon-staticmember

functiondefinitionorglobalfunctiondefinitionasyounormally

would,exceptthatthefunctionnamenowbecomesthe

keywordoperatorfollowedbythesymbolfortheoperatorbeing

overloaded.Forexample,thefunctionnameoperator+wouldbe

usedtooverloadtheadditionoperator(+).Whenoperatorsare

overloadedasmemberfunctions,theymustbenon-static,

becausetheymustbecalledonanobjectoftheclassand

operateonthatobject.

Touseanoperatoronclassobjects,thatoperatormustbe

overloadedwiththreeexceptions.Theassignmentoperator(=)

maybeusedwitheveryclasstoperformmemberwise

assignmentofthedatamembersoftheclasseachdatamember

isassignedfromthe"source"objecttothe"target"objectof

theassignment.Wewillsoonseethatsuchdefaultmemberwise

assignmentisdangerousforclasseswithpointermembers;we

willexplicitlyoverloadtheassignmentoperatorforsuchclasses.

Theaddress(&)andcomma(,)operatorsmayalsobeused

withobjectsofanyclasswithoutoverloading.Theaddress

operatorreturnstheaddressoftheobjectinmemory.The

commaoperatorevaluatestheexpressiontoitsleftthenthe



expressiontoitsright.Bothoftheseoperatorscanalsobe

overloaded.



[Page574]

Overloadingisespeciallyappropriateformathematicalclasses.

Theseoftenrequirethatasubstantialsetofoperatorsbe

overloadedtoensureconsistencywiththewaythese

mathematicalclassesarehandledintherealworld.For

example,itwouldbeunusualtooverloadonlyadditionfora

complexnumberclass,becauseotherarithmeticoperatorsare

alsocommonlyusedwithcomplexnumbers.

Operatoroverloadingprovidesthesameconciseandfamiliar

expressionsforuser-definedtypesthatC++provideswithits

richcollectionofoperatorsforfundamentaltypes.Operator

overloadingisnotautomaticyoumustwriteoperatoroverloadingfunctionstoperformthedesiredoperations.

Sometimesthesefunctionsarebestmadememberfunctions;

sometimestheyarebestasfriendfunctions;occasionallythey

canbemadeglobal,non-friendfunctions.Wediscussthese

issuesthroughoutthechapter.







[Page574(continued)]



11.3.RestrictionsonOperatorOverloading

MostofC++'soperatorscanbeoverloaded.Theseareshownin

Fig.11.1.Figure11.2showstheoperatorsthatcannotbe

overloaded.

Figure11.1.Operatorsthatcanbeoverloaded.

Operatorsthatcanbe

overloaded



















+



-



*



/



%



^



&



|



~



!



=



<



>



+=



-=



*=



/=



%=



^=



&=



|=



<<



>>



>>=



<<=



==



!=



<=



>=



&&



||



++



--



->*



,



->



[]



()



new



delete



new[]



delete[]



Figure11.2.Operatorsthatcannotbeoverloaded.

Operatorsthatcannotbeoverloaded

.



.*



::



?:



CommonProgrammingError11.1



Attemptingtooverloadanonoverloadableoperatorisa

syntaxerror.



Precedence,AssociativityandNumberof

Operands

Theprecedenceofanoperatorcannotbechangedby

overloading.Thiscanleadtoawkwardsituationsinwhichan

operatorisoverloadedinamannerforwhichitsfixed

precedenceisinappropriate.However,parenthesescanbeused

toforcetheorderofevaluationofoverloadedoperatorsinan

expression.



[Page575]

Theassociativityofanoperator(i.e.,whethertheoperatoris

appliedright-to-leftorleft-to-right)cannotbechangedby

overloading.

Itisnotpossibletochangethe"arity"ofanoperator(i.e.,the

numberofoperandsanoperatortakes):Overloadedunary

operatorsremainunaryoperators;overloadedbinaryoperators

remainbinaryoperators.C++'sonlyternaryoperator(?:)

cannotbeoverloaded.Operators&,*,+and-allhaveboth

unaryandbinaryversions;theseunaryandbinaryversionscan

eachbeoverloaded.



CommonProgrammingError11.2

Attemptingtochangethe"arity"ofanoperatorvia



operatoroverloadingisacompilationerror.



CreatingNewOperators

Itisnotpossibletocreatenewoperators;onlyexisting

operatorscanbeoverloaded.Unfortunately,thispreventsthe

programmerfromusingpopularnotationslikethe**operator

usedinsomeotherprogramminglanguagesforexponentiation.

[Note:Youcouldoverloadthe^operatortoperform

exponentiationasitdoesinsomeotherlanguages.]



CommonProgrammingError11.3

Attemptingtocreatenewoperatorsviaoperator

overloadingisasyntaxerror.



OperatorsforFundamentalTypes

Themeaningofhowanoperatorworksonobjectsof

fundamentaltypescannotbechangedbyoperatoroverloading.

Theprogrammercannot,forexample,changethemeaningof

how+addstwointegers.Operatoroverloadingworksonlywith

objectsofuser-definedtypesorwithamixtureofanobjectofa

user-definedtypeandanobjectofafundamentaltype.



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

Chapter 11. Operator Overloading; String and Array Objects

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

×