C++面向對象程序設計雙語教程(第3版)課件 ch07Polymorphism and Virtual Functions、ch08Templates_第1頁
C++面向對象程序設計雙語教程(第3版)課件 ch07Polymorphism and Virtual Functions、ch08Templates_第2頁
C++面向對象程序設計雙語教程(第3版)課件 ch07Polymorphism and Virtual Functions、ch08Templates_第3頁
C++面向對象程序設計雙語教程(第3版)課件 ch07Polymorphism and Virtual Functions、ch08Templates_第4頁
C++面向對象程序設計雙語教程(第3版)課件 ch07Polymorphism and Virtual Functions、ch08Templates_第5頁
已閱讀5頁,還剩85頁未讀 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

PolymorphismandVirtualFunctionsC++面向對象程序設計雙語教程(第3版)Chapter701PolymorphismThekeyideabehindOOPispolymorphism.PolymorphismisderivedfromaGreekwordmeaning“manyforms”.Wespeakthetypesrelatedbyinheritanceaspolymorphictypes,becauseinmanycaseswecanusethe"manyforms3ofaderivedorbasetypeinterchangeably.IntroductiontoPolymorphismPolymorphismInprogramminglanguages,polymorphismmeans

that

some

codesoroperationsor

objectsbehavedifferentlyindifferentcontexts.Forexample,the+operatorinC++implementtheadditionoperationwithdifferentdataordifferenttypes.IntroductiontoPolymorphismPolymorphismPolymorphismisakeyfeatureofobject-orientedprogrammingthatallowsthevaluesofdifferentdata

typestobehandledbyusingauniforminterface.多態(tài)性是一個面向對象程序設計的關鍵特性,它允許使用統(tǒng)一的接口處理不同數(shù)據(jù)類型。PolymorphismThepurposeofpolymorphismistoimplementastyleofprogrammingcalledmessage-passingintheliterature,inwhichtheobjectsofvarioustypesdefineacommoninterfaceofoperationsforusers.PolymorphismTypically,polymorphismoccurswhenthereisaclasshierarchyinwhichtheclassesarerelatedbyinheritance.PolymorphismBindingWhenaC++programisexecuted,itexecutessequentially,beginningatthetopof

functionmain.Whenafunctionealliseneountered,thepointofexecutionjumpstotheinitial

pointofthefunctionbeingcalled.HowdoestheCPUknowtodothis?PolymorphismWhenaprogramiscompiled,thecompilerconvertseachstatementinyourC++programintooneormorelinesofmachinelanguage.Eachlineofmachinelanguageisgivenitsownuniquesequentialaddress.Thisisnodifferentforfunctionswhenafunctionisencountered,itisconvertedintomachinelanguageandgiventhenextavailableaddress.Thus,eachfunction

endsupwithauniquemachinelanguageaddress.PolymorphismBindingisaprocessthatisusedtoconvertidentifiers

intomachinelanguageaddresses.Inotherwords,bindingisanassociation,suchasbetweenidentifiers

andoperations.Therearetwotypesofbindingaccordingtothetimeatwhichabindingtakesplace,i.e.staticbindingand

dynamicbinding.綁定是一種用于將標識符(如變量和函數(shù)名)轉換成機器語言地址的過程。換句話說,綁定是一種關聯(lián),例如在標識符(變量或函數(shù)名)和操作(類型或特定函數(shù)體)之間的關聯(lián)。根據(jù)綁定發(fā)生的時間,有兩種類型的綁定,即靜態(tài)綁定和動態(tài)綁定。PolymorphismStaticBindingBydefault,Ct+matchesafunctioncallwiththecorrectfunctiondefinitionatcompiletime.Thisiscalledstatiebinding.Thiskindofbindingisalsoknownaseompile-timebinding.Forexample,theoperatoroverloadingandthefunctionoverloadingmentionedinthepreviouschaptersarethatthecompilerassociatestheoperatorfunctionsandoverloadedfunctionswiththeirdefinitionsatcompile-time.PolymorphismEachfunctionhasauniqueaddress.Thus,whenthecompilerencountersafunctioncall,itreplacesthefunctioncallwithamachinelanguageinstructionthattellstheCPUtojumptotheaddressofthefunction.PolymorphismWhenthecompilermatchesafunctioncallwiththecorreetfunctiondefinitionatrun-time,thisiscalleddynamiebinding.Thecodeassociatedwiththeproceduredoesnotknowuntiltheprogramisexecuted.Thiskindofbindingisalsoknownasrun-timebinding.Youcandeclare

afunctionwiththevirtualkeywordifyouwantthecompilertousedynamicbindingforthatspecificfunction.DynamicBindingPolymorphism02VirtualFunctionsAvirtualfunctionisamemberfunctionofthebaseclassandisredefinedbythederivedclass.Thecompilerwillguaranteethecorrectcorrespondencebetweenobjectsandthefunctionsappliedtothem.Avirtualfunctioniscreatedusingthekeywordvirtualwhichprecedesthenameofthefunction.VirtualFunctionsForexample,supposeagraphicsprogramincludesseveraldifferentshapes:acubeandacuboid,andsoon,asshowninFigure7-1.VirtualFunctionsToenablethiskindofbehavior,wedeclarefunctionvolumeinthebaseclassasavirtualfunction,andweoverridefunctionvolumeineachofthederivedclassestocalculatethevolumeofappropriateshape.VirtualFunctionsWhenaderivedclassinheritstheclasscontainingthevirtualfunction,ithastheabilityto

redefinethevirtualfunctions.Avirtualfunctionhasdifferentfunctionalityinthederivedclass.Thevirtualfunetionimplementsthephilosophyofoneinterfaceandmultiplemethods.VirtualFunctionsVirtualfunetionscanbeaccessedbyusingabaseclasspointer.Apointertothebaseclasscanbecreated.Abaseclasspointercancontaintheaddressofthederivedobjectasthederivedobjectcontainsthesubsetofabaseclassobject.VirtualFunctionsEveryderivedclassisalsoabaseclass.Whenabaseclasspointercontainstheaddressofthederivedclassobject,atruntime,whichversion

ofthevirtualfunctionbeingcalleddependsonthetypeofobjectcontainedbythepointer.

Hereisaprogramwhichillustratestheworkingofvirtualfunctions.VirtualFunctionsOnceafunctionisdeclaredasvirtual,itremainsvirtualallthewaydowntheinheritancehierarchy

fromthatpoint,evenifthatthefunctionisnotexplicitlydeclaredasvirtualwhenaclassoverrides

it.Ifthememberfunctioninthederivedclassisvirtual,thekeywordvirtualcanbeomittedinthe

derivedclass.Butthekeywordvirtualcannotbeomittedinthebaseclass.VirtualFunctionsExtensibilityIfthevolumefunetionisdefinedasvirtualinthebaseclass,youcanaddasmanynewclasstypesasyouwantwithoutchangingthefnfunction.Inawell-designedOOPprogram,mostorallyourfunetionswillfollowthemodeloffunctionfnandcommunicateonlywiththebase-classinterface.VirtualFunctionsExtensibilitySuchaprogramisextensiblebecauseyoucanaddnewfunctionalitybyinheritingnewdatatypesfromthecommonbaseclass.Thefunetionsthatmanipulatethebase

classinterfacewillnotneedtobechangedatalltoaccommodatethenewclasses.HereistheShapeexamplewithmorevirtualfunctionsandanumberofnewclasses,allofwhichworkcorrectlywiththeold,unchangedfnfunction.VirtualFunctionsTheextensibilityofclasshierarchymentionedinExample7-3isshowninFigure7-2.VirtualFunctionsHowcandynamiebindinghappenbyvirtualfunctions?Alltheworkgoesonbehindthescenesbythecompiler,whichinstallsthenecessarydynamicbindingmechanismwhenyouaskitto(youareaskedtocreatevirtualfunctions).PrincipleofVirtualFunctionsVirtualFunctionsBecauseprogrammersoftenbenefitfromunderstandingthemechanismofvirtualfunctionsinC++,thissectionwillelaborateonthe

waythecompilerimplementsthismechanism,Thevirtualkeywordtellsthecompilerthatitshouldnotperformstaticbinding.PrincipleofVirtualFunctionsVirtualFunctionsIneachclasswithvirtualfunctions,itsecretlyplacesapointer,calledthevpointer(abbreviatedasVPTR),whichpoints

totheVTABLEforthatobject,asshowninFigure7-3.VirtualFunctionsVirtualDestructorsOnethingrecommendedfortheclasswithpointermembervariablesisthattheclassshouldhavethedestructor(seeSection4.6.2).Thedestructorisautomaticallyexecutedwhentheclassobjectgoesoutofthescope.Then,iftheobjectcreatesdynamicobjects,thedestructorcanbedesignedtodeallocatethestorageforthem.VirtualFunctionsThebaseclassdestructorshouldalwaysbevirtual.Supposeyouusethedeleteoperatorwithabaseclasspointertoaderivedclassobjecttodestroythederivedclassobject.Ifthebaseclassdestructorisnotvirtual,butlikeanormalmemberfunction,thenthedeleteoperator

callsthedestruetorforthebaseclass,butnotthedestructorforthederivedclass.VirtualFunctionsIfnoneofthedestructorshasanythingimportanttodo(likedeallocatingmemoryobtainedwith

delete),thenvirtualdestructorsaren'tnecessary.But,ingeneral,toensurethatderivedclassobjects

aredestroyedproperly,youshouldmakevirtualthedestruetorsinallbaseclasses.VirtualFunctionsWehaveintroducedfunctionoverloadingandfunctionoverridingintheprevioussections.Thesetermsaresimilar,andtheydosimilarthings.Whenyouoverrideamemberfunetionoftheclass,youcreateamemberfunetioninaderivedclasswiththesamenameasafunetioninthebaseclassandthesamesignature.FunctionOverloadingandFunctionOverridingVirtualFunctionsIfwedefineafunctionasvirtualinthebaseclass,thefunctionwiththesame

name

andsamesignaturebutnokeywordvirtualinthederivedclassisalsothevirtualfunctionbecauseofoverriding.VirtualFunctions03AbstractBaseClassesOfteninadesign,youwantthebaseclasstopresentonlyaninterfaceforitsderivedclasses.Thatis,youdon'tallowanyonetocreateanobjectofthebaseclass,butonlywanttoupcasttoitsothatitsinterfacecanbeused.Thisisaccomplishedbymakingthatclassabstraet.AbstractBaseClassesAbstractbaseclassesactastheexpressionsofgeneralconceptsfromwhichmorespecific

classescanbederived.Ifanabstractbaseclasscannotbeinstantiated,itexistsextensivelyforinheritanceandit

mustbeinherited.AbstractBaseClassesTherearescenariosinwhichitisusefultodefineaclassthatisnotintendedtobeinstantiatedbecausesuchclassesnormallyareusedasbase-classesininheritance

hierarchies.AbstractBaseClassesThisclassmustbeinherited.Thisclassismostlyusedasabaseclass.Youcannotcreatean

objectofanabstractelasstype;however,youcanusepointersandreferencestoabstractclasstypes.AbstractBaseClassesAclassthatcontainsatleastonepurevirtualfunctionisconsideredasanabstractclass.Theclassesderivedfromtheabstractclassmustimplementthepurevirtualfunctionorthey,too,areabstractclasses.AbstractBaseClassesApurevirtualfunctionisafunctionwhichcontainsnodefinitioninthebaseclass.Youdeclareapurevirtualfunctionbyusingapurespecifier(=0)inthedeclarationofavirtualmemberfunctionintheclassdeclaration.純虛函數(shù)是一個在基類中沒有定義的函數(shù)。在類聲明時使用pure說明符(=0)將一個虛成員函數(shù)聲明為純虛函數(shù)。AbstractBaseClassesAclasswhichcontainsoneormorepurevirtualfunctioniscalledanabstractbaseclass.Abstractbase

classcsactasexpressionsofgeneralconceptsfromwhichmorespecificclassescanbederived.包含一個或多個純虛函數(shù)的類稱為抽象基類。抽象基類作為通用概念的表示,從中可以導出更多具體的類。AbstractBaseClassesThestatementinLine6tellsthecompilertoreserveaslotforafunetionintheVTABLE,butnottoputanaddressinthatparticularslot.Evenifonlyonefunctioninaclassisdeclaredaspurevirtual,theVTABLEisincomplete.AbstractBaseClassesIftheVTABLEforaclassisincomplete,whatisthecompilersupposedtodowhen

someonetriestomakeanobjectofthatclass?Itcannotsafelycreateanobjectofanabstractclass,soyougetanerrormessagefromthecompiler.Thus,thecompilerguaranteesthepurityoftheabstractclass.Bymakingaclassabstract,youcanensurethattheclientprogrammercannotmisuseit.AbstractBaseClassesPurevirtualfunctionsarehelpfulbecausetheymakeexplicittheabstractnessofaclass

andtellboththeuserandthecompilerhowitwasintendedtobeused.AbstractBaseClasses04CaseStudy:AMini-SystemWedesignamini-systemthatineludesdifferenttypesofpeopleintheuniversity.Therearefiveclasses,thatis,Person,Student,Employee,F(xiàn)acultyandStaff,tobedefined.AclassnamedPersonhastwoderivedclassesnamedStudentandEmployee.MakethederivedclassesFaculty

andStaffofEmployee.CaseStudy:AMini-SystemApersonhasaname,address,phonenumberande-mailaddress.A

studenthasaclassstatus(freshmen,sophomore,junior,orsenior).Anemployeehasanoffice,salary,anddate-hired.DefineaclassnamedDatethatcontainsthefieldsyear,monthandday.CaseStudy:AMini-SystemAfacultymemberhasofficehoursandarank.Astaffmemberhasatitle.Defineaconstantvirtualto

StringfunctioninthePersonclassandoverrideitineachclasstodisplaytheclassnameand

theperson'sname.CaseStudy:AMini-SystemTheUMLdiagramofthesesixclassesisdescribedinFigure7-4.CaseStudy:AMini-System謝謝觀看C++面向對象程序設計雙語教程(第3版)TemplatesC++面向對象程序設計雙語教程(第3版)Chapter801Introduction

to

TemplatesManyC++programsusecommondatastructureslikestacks,queuesandlists.Aprogrammayrequireaqueueofcustomersandaqueueofmessages.Onecouldeasilyimplementaqueueofcustomers,thentaketheexistingcodeandimplementaqueueofmessages.IntroductiontoTemplatesTheprogramgrows,andnowthereisaneedforaqueueoforders.Sojusttakethequeueofmessagesandconvertthattoaqueueoforders(copy,paste,find,andreplace).Needtomakesomechangestothequeueimplementation?IntroductiontoTemplatesNotaveryeasytask,sincethecodehasbeenduplicatedinmanyplaces.Reinventingsourcecodesisnotanintelligentapproachinanobject-orientedenvironmentwhichencouragesreusability.IntroductiontoTemplatesItseemstomakemoresensetoimplementaqueuethatcancontainanyarbitrarytyperatherthanduplicatingcode.Howdoesonedothat?Theansweristousetypeparameterization,ormorecommonlyreferredtoastemplates.IntroductiontoTemplatesToavoidrewritingcodethatwouldbeidenticalexceptfordifferenttypes.Sometimesyoudonotsimplyrelyonimplicittypeconversionorpromotionmatch,andyoucannotstuffeverythingintoaclasshierarchy.IntroductiontoTemplatesGenericprogrammingisastyleofprogramminginwhichalgorithmsarewrittenintermsoftypes

to-be-specified-later.Thenthesetypesworkingasparametersareinstantiatedwhenspecifictypesareneeded.Templatesprovidedirectsupportforgenericprogramming,thatis,programmingusingtypesasparameters.TheC++templatemechanismallowsatypetobeaparameterinthedefinitionofaclassorafunction.IntroductiontoTemplatesC++providestwokindsoftemplates:classtemplatesandfunctiontemplates.Usefunctiontemplatestowritegenericfunctionsthatcanbeusedwitharbitrarytypes.Forexample,onecanwritesearehingandsortingroutinesthatcanbeusedwithanyarbitrarytype.ThegenericalgorithmsintheStandardTemplateLibrary(i.e.STL)havebeenimplementedasfunctiontemplates,andthecontainershavebeenimplementedasclasstemplates.IntroductiontoTemplates02FunctionTemplatesLet'simaginethatwewanttowriteafunctiontocomparetwovaluesandindicatewhetherthefirstislessthan,equalto,orgreaterthanthesecondone.Inpractice,wewouldwanttodefineseveralsuchfunctions,eachofwhichcouldcomparevaluesofagiventype.DefinitionofFunctionTemplatesFunctionTemplatesThetwofunctionsarenearlyidentical.Theonlydifferencebetweenthemisthetypeoftheirparameters.Thefunetionbodyisthesameineachfunction.Havingtorepeatthebodyofthefunctionforeachtypethatwecompareistediousanderror-prone.FunctionTemplatesMoreimportantly,we

needtoknowinadvanceallthetypesthatwemighteverwanttocompare.Thisstrategy

cannotworkifwewanttobeabletousethefunctionontypesthatwedon'tknowabout.

Therefore,wethinkthatthesecomparefunctionsneedtobedefinedasagenericfunetion.FunctionTemplatesFunctionTemplateInstantiationWhenafunctiontemplateisfirstcalledforeachtype,thecompilercreatesaninstantiation.Eachinstantiationisaversionofthetemplatedfunctionspecializedforthetype.Thisinstantiationwillbeealledeverytimethefunctionisusedforthetype.FunctionTemplatesWhenthecompilerencountersthiscalltoatemplateinstantiation,itusesthetemplatetoautomaticallygenerateafunctionreplacingeachappearanceofTbythetypepassedastheactualtemplateparameter(intinthiscase)andthencallsit.Thisprocessisautomaticallyperformedbythecompilerandisinvisibletotheprogrammer.FunctionTemplatesFunctionTemplatewithDifferentParameterTypesSincethefunctiontemplateinExample8-1inchidesonlyonetemplateparameter(typenameT)andthefunctiontemplateitselfacceptstwoparameters,bothofthesameTtypes,wecannotcallourfunctiontemplatewithtwoobjectsofdifferenttypesasarguments.FunctionTemplatesFunctionTemplateOverloadingFunctiontemplatesandoverloadingareintimatelyrelated.Onecandeclareseveralfunctiontemplateswiththesamenameandevendeclareacombinationoffunctiontemplatesandordinaryfunctionswiththesamename.Whenanoverloadedfunctioniscalled,overloadingresolutionisnecessarytofindtherightfunctionortemplatefunction

toinvoke.FunctionTemplates03ClassTemplatesJustaswecandefinefunctiontemplates,wecanalsodefineclasstemplates.Forexample,a"stack3isadatastruetureintowhichweinsertitemsatthetopandretrievethoseitemsinlast-in,first-outorder.Itisindependentofthetypeoftheitemsbeingplacedinthestack.Normally,aStackclasscanbedefinedbyaspecifieddatatype.DefinitionofClassTemplatesClassTemplatesIfyouwanttocreatea

wonderfulopportunityforsoftwarereusability,youneedtodefineagenericStaekclassandtoinstantiatetheclassthatisthetype-specificversionsofthegenericStackclass.C++providesthiscapabilitythroughtheclasstemplate.ClassTemplatesAclasstemplateiscalledaparameterizedtype,becauseitrequiresoneormoretypeparameterstospecify

howtocustomizea"genericclass"templatetoformaclass-templatespecialization.類模板稱為參數(shù)化類型,因為它們需要一個或多個類型參數(shù)來指定如何自定義“通用類”模板以形成類模板專用化。ClassTemplatesClassTemplateInstantiationItiseasytouseaclasstemplate.Createtherequiredclassesbypluggingintheactualtypeforthetypeparameters.Thisprocessiscommonlyknownas

"Instantiatingaelass".HereisasampledriverclassthatusesclasstemplateStack.ClassTemplatesTheprocessofgeneratingaclassdeclarationfromatemplateclassandatemplateargumentisoftencalledclasstemplateinstantiation.從模板類和模板參數(shù)生成類聲明的過程通常稱為類模板實例化。ClassTemplatesNow,letusconsidertheuserprogramthatexercisesclasstemplateStack.Althoughtemplatesoffersoftware-reusabilitybenefits,rememberthatmultipleclass-templatespecializationsareinstantiatedinaprogram(atcompiletime),eventhoughthetemplateiswrittenonlyonce.ClassTemplatesTheprogrambeginsbyinstantiatinganobjeetdoubleStaekofsize5inLine5.ThisobjectisdeclaredtobeofclassStack<double>(pronounced

"Stackofdouble").ThecompilerassociatestypedoublewithtypeparameterTintheclasstemplatetoproducethesourcecode

foraStackclassoftypedouble.ClassTemplatesClassStackprovidestheisFullfunction,whichtheprogrammercanusetodeterminewhetherthestackis

fullbeforeattemptingapushoperation.Thiswouldavoidthepotentialerrorofpushingontoa

fullstack.ClassTemplates04Non-TypeParametersforTemplatesBesidesthetemplateargumentsthatareprecededbythetypenamekeywords,which

representtypes,templatescanalsohaveregulartypedparameters,likethosefoundinfunctions.Asanexample,takealookatthisclasstemplatethatisusedtocontainsequencesofelements.Non-TypeParametersforTemplatesInthisexample,integerNisanon-typetemplateparameter.Whentheobjectsofthe

templatearecreatedinLines24and25,aninteger5isdirectlypassedintoN.Itisalsopossibletosetdefaultvaluesortypesforclasstemplateparameters.Non-TypeParametersforTemplates05AbstractBaseClassesClasstemplatescaninheritorbeinheritedfrom.Formanypurposes,thereisnothing

significantlydifferentbetweenthetemplateandnon-templatescenarios.DerivationandClassTemplatesHowever,thereisoneimportantsubtletywhenderivingaclasstemplatefromabaseclassreferr

溫馨提示

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

最新文檔

評論

0/150

提交評論