![西北工業(yè)大學(xué)數(shù)據(jù)結(jié)構(gòu)課件由計(jì)算機(jī)學(xué)院王慶老師制作_第1頁](http://file4.renrendoc.com/view/f20ce55f6ccb644549dc3ff41b76a7df/f20ce55f6ccb644549dc3ff41b76a7df1.gif)
![西北工業(yè)大學(xué)數(shù)據(jù)結(jié)構(gòu)課件由計(jì)算機(jī)學(xué)院王慶老師制作_第2頁](http://file4.renrendoc.com/view/f20ce55f6ccb644549dc3ff41b76a7df/f20ce55f6ccb644549dc3ff41b76a7df2.gif)
![西北工業(yè)大學(xué)數(shù)據(jù)結(jié)構(gòu)課件由計(jì)算機(jī)學(xué)院王慶老師制作_第3頁](http://file4.renrendoc.com/view/f20ce55f6ccb644549dc3ff41b76a7df/f20ce55f6ccb644549dc3ff41b76a7df3.gif)
![西北工業(yè)大學(xué)數(shù)據(jù)結(jié)構(gòu)課件由計(jì)算機(jī)學(xué)院王慶老師制作_第4頁](http://file4.renrendoc.com/view/f20ce55f6ccb644549dc3ff41b76a7df/f20ce55f6ccb644549dc3ff41b76a7df4.gif)
![西北工業(yè)大學(xué)數(shù)據(jù)結(jié)構(gòu)課件由計(jì)算機(jī)學(xué)院王慶老師制作_第5頁](http://file4.renrendoc.com/view/f20ce55f6ccb644549dc3ff41b76a7df/f20ce55f6ccb644549dc3ff41b76a7df5.gif)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
C++reviewDr.QingWangTransitioningtoC++C++IntroducedBasicC++ProgrammingMemoryManagementMechanismsforCodeReuseandAbstractionC++IntroducedC++BackgroundCompilingandRunningaC++ProgramC++BackgroundHistoryKeyFeaturesHistoryC++isamodernobject-orientedprogramminglanguagethatsupportsmanyofthesamefeaturesasJava,includingclasses,inheritance,polymorphism,andexceptions.KeyFeaturesC++isstronglytyped.Thissimplymeansthateveryobjectmustbelongtoacertaintypeandthatoperationssuchasassignmentorcomparisonareonlypermittedbetweenobjectsofthesametype.C++hastheconceptofaclass,atypeofrecordthatcombinesdatamembersandthefunctionsthatoperateonthedata.Ignoringvariousminordifferences,classesinC++areverysimilartoclassesinJava.
KeyFeaturesC++supportsparameterizedtypes,ortemplates.Templatesmakeitpossibletodefine,say,asinglevectorclassthatworksforBooleans,characters,integers,reals,andsoon.C++supportsinheritance,amechanismthatmakesitpossibletobuildnewclasses(calledderivedclasses)ontopofanexistingclass(calledthebaseclass)withouthavingtoreiteratethebaseclassdesignforeachnewclass.
KeyFeaturesC++supportspolymorphism.InC++,polymorphismisachievedthroughtheuseofvirtualfunctionsandpointervariables.Togetherwithinheritance,thisturnsC++intoafull-fledgedobject-orientedlanguage.C++comeswithtwolibrariesknownastheStandardLibraryandtheStandardTemplateLibrary(STL)—bothofwhichextendthecapabilitiesofthebaselanguage.
KeyFeaturesC++hasaverylargeuserbase.Fromallovertheworld,publicandprivatecompanies,governmentagencies,academics,andhobbyistsuseC++inalltypesofinterestingwaysandapplications.Amajorbenefitofthislargeuserbaseisthewideavailabilityofdifferenttools,libraries,andtutorials,allrelatedtosomeaspectofthelanguage.BasicC++ProgrammingDataTypesSpecifyingClassesInputandOutputThePreprocessorASide-By-SideExampleDataTypesFundamentalDataTypesStringsArraysVectorsCreatingNewDataTypeNamesFundamentalDataTypesThefundamentaldatatypesthatC++supportsaresimilartotheprimitivedatatypesofJava.ThefollowingtablelistseachofthefundamentaldatatypesofC++andthecorrespondingJavaprimitivedatatype.C++typeJavatypeboolbooleancharcharintintshortshortlonglongfloatfloatdoubledoubleExample1Read-onlyvariableLikeJava,C++containsamechanismtocreate"read-only"variables.C++usesthekeywordconsttoallowprogrammerstocreate"read-only"variables.Thiskeywordsignalsthatthevariablebeingdeclaredcannotbemodifiedafteritisinitialized.ThekeywordconstofC++isanalogoustothekeywordfinalinJava.Example2StringsInC++,thestringdatatypeprovidesthenecessaryabstractiontoallowC++programmerstoworkwithcharacterstrings.IfaC++programrequiresthestringtype,theprogrammermustrefertothelibrarythatdefinesthistype.ThefollowinglistingillustratestheC++stringdatatypeinaction.Example3ArraysC++providesbasicsupportforasequenceofhomogeneousdataobjectsthrougharrays.BothsimilaritiesanddifferencesexistbetweenJavaarraysandarraysinC++.Example4VectorsThevectordatatypeprovidesamuchsaferalternativetoabasicC++array.InC++,asinJava,vectorsexistasfeature-richarray.Forexample,unlikeanarrayinC++avectorhasabuiltinfunctionthatreturnsthesizeofthevector.Vectorsalsoprovideboundscheckingsupport,andunlikearrays,theyautomaticallyincreaseinsizewhentheneedarises.CreatingNewDataTypeNamesItispossibleinC++foraprogrammertocreateadditionalnamesforexistingdatatypes.Creatinganothernameusesthekeywordtypedef.Thesyntaxtocreateanewnameisasfollows.
typedeftype-expression
new-name;
Example5SpecifyingClassesBasicSyntaxConstructorsTheDestructorDeclarationvs.DefinitionBasicSyntaxTheclassisthebasicunitofabstractioninC++.AsinJava,wecanuseclassestospecifyandtheninstantiateobjects.ThebasicsyntaxinvolvedinspecifyingaclassandininstantiatinganobjectdiffersbetweenJavaandC++.Let'slookfirstatasimpleclassspecifiedinJava,andthenthecorrespondingversioninC++.Example1(ClassinJAVA)Example2(ClassinC++)ConstructorsConstructorsarethemethodsofaclassthatdefinewhatactionstotakewhencreatinganobject.AC++classcanhavemultipleconstructors.Thisallowsvariationinobjectinstantiationsincedifferentnumbersandtypesofparameterscanexistineachconstructor.example3example4TheDestructorAdestructorisaspecialmemberfunctionofaC++classcalledwhenanobject'slifetimeends.Likeacopyconstructor,onlyonedestructorcanexistforaclass.Sincetheyexecutewhenanobject'slifetimeends,destructorstypicallydefinetheactionsnecessarytoreleaseanyresourcesthatanobjectmaybeusing.example5Declarationvs.DefinitionInthisdiscussiononthespecificationofclassesinC++,theterm"definition"hasbeenusedregardingfunctions.Whenwe"define"afunction,wedictatethefunction'sbehaviorthroughthecodethatexistswithinthecurlybraces.The"declaration"ofafunction,ontheotherhand,onlyspecifiestheinterfaceofthefunction.Thisinterfaceincludesthefunctionname,thereturntype,andthelistofparametersandtheirtypes.example6example7內(nèi)嵌函數(shù)ClassCat{Public:Cat(intage);~Cat();intgetAge()const{returnitsAge;}//inlineoidSetAge(intage){itsAge=age;}//inlinePrivate:intitsAge;};Example8-1Example8-2InputandOutputStreamsUsingtheStandardStreamsFileInputandOutputSomeCommonPitfallsStreamsInputandoutputinC++isbasedontheconceptofastream.Astreamisasequenceofbytesthatflowfromsomethingtosomethingelse.Theprocessofoutputinvolvesmovingbytes,oneatatime,fromaprogramtoadevice.Thisdevicecouldbeamonitor,aprinter,orevenafileonaharddrive.Inputistheopposite.Inputinvolvestheflowbytesfromadevice(akeyboard,afile,anetworkconnection)intotheprogram.Exampl1UsingtheStandardStreamsThreespecificstreamsarealwaysavailablethroughoutthelifetimeofeveryC++program.
standardinput,standardoutput,andstandarderrorstreams.Eachofthesestandardstreamshasaspecificuse.Thestandardinputstreamreadsdatafromtheconsole,thestandardoutputstreamwritesdatatotheconsole,andthestandarderrorstreamdisplayserrormessagestotheconsole.Example2User-definedclassC++programmerscandefinehowtheclassestheycreateinteractwithstreamsusingthe<<and>>operators.Thisiscalledoperatoroverloading.Remember,streamclassesdefinetheinsertion(<<)andextraction(>>)tooperateinaspecialway,formanydifferentdatatypes.Whetherusedwithintegers,floatingpointnumbers,orstrings,theseoperatorsoutputandformatdataaccordingly.Wecanalsodefinethebehavioroftheseoperatorsforclassesthatwecreate.Thisallowsinputandoutputcodeforuser-definedclassestoresembleinputandoutputforbuilt-intypes.Example3-1Eample3-2FileInputandOutputFilebasedinputandoutputissimilartothemechanismsforkeyboardandscreenI/O.Themaindifferenceisthatprogrammersmustexplicitlyopenandclosefiles.Inpseudocode,agenericprogramthatreadsinputfromafilemightlooklikethis.Example4-1Example4-2Example4-3SomeCommonPitfallsStreaminputexpectswhitespacetoseparatethevaluesitreads.Whitespaceconsistsofspaces,horizontalandverticaltabs,newline,andcarriagereturncharacters.ManyprogrammersnewtoC++donotrealizethatstreaminputalsoignoresextrawhitespacebydefault.AcommonmistakeformanynewC++programmersistoreversethe<<and>>operators.PitfallsofI/OstreamAnothercommonpitfallthatmostnewC++programmersencounteroccurswhentheytrytoreadalineoftextintoastringvariable.Usingthegetlinefunctionfoundinthestringlibraryistheproperwaytoinputanentirelineoftext.
charline[20];cin.getline(line,20);ThePreprocessorTextSubstitutionFileInclusionMacroSubstitutionConditionalCompilationAnExample:AssumptionVerificationTextSubstitutionThepreprocessorisatoolthatC++programmersusetomanipulatethecontentsofsourcecodefilespriortocompilation.FileInclusionFileinclusionisafeatureoftheC++preprocessorthatallowsasourcecodefiletousesharedcode.Weconsidersharedcodetobeclassesorfunctionsdeclaredinotherfiles.InC++,wecanonlyaccessasharedclassorfunctionbyincludingitsdeclarationintoourprogram.Example1MacroSubstitutionTheC++preprocessorcanperformaprogrammerdefinedtextsubstitutionthroughoutanentiresourcecodefile.Thisisknownasmacrosubstitution.Programmersdefineamacrousingthe#definepreprocessordirective,whichcantakethefollowingform.
#defineidentifier
replacement-text
#defineidentifier(identifier,identifier,...)replacement-text
Example2-1Example2-2example#include<iostream>#include<cstdlib>#defineADD(x,y)x+yusingnamespacestd;intmain(){intx=3*ADD(1,2)*4cout<<x<<endl;return0;}ConditionalCompilationBeyondmacrosubstitution,amoreimportantreasontouse#defineistosupportconditionalcompilation.Using#define,andsomeotherpreprocessordirectives,wecaninstructthecompilertocompileonlycertainsectionsofoursourcecode.Thisisusefulinmanycircumstances,oneofwhichisforinsertingdebuggingcodethatcanbeeasilyenabledanddisabled.Belowweseeanexamplethatusesthe#define,#if,and#endifdirectives.Example3Asidebysideexamplebankaccount.hbankaccount.cppmain.cpp-1main.cpp-2MemoryManagementPointersParameterPassingMechanismsDynamicMemoryManagementpointerApointerisavariablethatstoresthememoryaddressofanothervariable.Apointervariableisuniqueinthatitstoresthememoryaddressofanothervariable.Amemoryaddressisthespecificlocationinmainmemorywhereavariableexistsduringprogramexecution.pointerProgrammersusepointerstoindirectlyaccessandmanipulateothervariables.Thisaccessandmanipulationisconsidered"indirect"sinceitisaccomplishedusingapointerinsteadoftheactualvariablebeingmodified.Indirectionallowsthecreationofcomplexdatastructuresandpowerfulalgorithms.Forinstance,withoutpointersandindirectionitwouldnotbepossibletocreatealinkedlistdatastructure.BasicOperationsofpointerDeclarationandInitializationDereferencePointerArithmeticDeclarationandInitializationThedeclarationofapointervariablerequirestheuseofsomeunfamiliarsyntax.Apointerdeclarationmustprefixitsvariablenamewithanasterisk(*).Thissignifiestothecompilerthatthevariabledeclaredisapointer.DeclarationandInitializationPointerinitializationalsorequiressomenewsyntax.Wecannotsimplyinitializeapointertoanon-pointervariablebecausepointersstorememoryaddressesandnotregularvalues.Instead,wemustobtainthememoryaddressofthevariable.Theaddress-of(&)operatorreturnsthememoryaddressofwhereavariableisstored.DereferenceIndirectaccessandmanipulationofvariablesusingpointersisaccomplishedusingthedereferenceoperator.Aprogrammerappliesthedereferenceoperator(*)toaccessormodifythevalueofthevariablepointedtobyapointer.ExampleDereferenceWecanonlysafelydereferencepointersthatpointtovalidmemoryaddresses.Dereferencingpointersthathavenotbeeninitializedtovalidmemoryaddressescausesarun-timeerror.Onetechniqueusedtoavoidthisproblemistheinitializationofpointervariablestothenullpointer.PointerArithmeticPointerarithmeticistheuseofadditionandsubtractiontochangethememorylocationthatapointerstores.Theseoperationsareallrelativetothememorylocationcurrentlystoredinapointer.ExampleParameterPassingMechanismsPassbyValuePassbyReferencePassbyPointerPassbyValuePassbyvalueisthedefaultparameterpassingmechanisminC++.Whenaparameterispassedbyvaluetoafunction,acopyoftheparameteriscreatedandgiventothefunction.Thisisimportant,sinceifwemakeachangetoaparameterthatispassedbyvalue,theoriginalvariablewillremainunchanged.Ourchangeismadetoacopyoftheoriginalvariable.ExamplePassbyValueC++canalsopassobjectsbyvalue.ExamplePassbyReferenceUnlikepassbyvalue,copiesarenotmadeofvariablesthatarepassedbyreference.Instead,acalledfunctionreceivesareference,oralias,totheactualparametersuppliedbythecallingfunction.Forthisreason,passbyreferenceisusedtobuildfunctionsthatcanmodifythevariablesinthecallingfunction.Onecommonuseofpassbyreferenceistocreatefunctionsthatcanmodifythevariablespassedtothembyacallingfunction.PassbyReferencePassingaparameterbyreferenceisalsousedasamechanismtopasslargeobjectstofunctions.Whenobjectsarelarge,passbyvaluecanresultintime-consumingcopyoperations.Passbyreferenceismoreefficientbecauseitdoesnotinvolvecopying.#include<iostream>usingnamespacestd;classCat{public:Cat();Cat(Cat&);~Cat();}Cat::Cat(){cout<<"CatConstructor..\n";}Cat::Cat(Cat&){cout<<"CatcopyConstructor..\n";}Cat::~Cat(){cout<<"CatDestructor..\n";}Catfunction1(Catthecat);Cat&function2(Cat&thecat);intmain(){cout<<"makingcat..\n";Catfrisky;cout<<"callingfunction1..\n";function1(frisky);cout<<"callingfunction2..\n";function2(frisky);return0;}makingcat..CatConstructor..callingfunction1..CatcopyConstructor..function1return..CatcopyConstructor..CatDestructor..CatDestructor..callingfunction2..function2return..CatDestructor..Pressanykeytocontinueconstreferencepassapointerbyreferencereturnbyreference#include<iostream>usingnamespacestd;enumerr_cod(sucess,error);err_codefactor(int,int&,int&);intmain(){intnum,squ,cub;err_codresult;cout<<"enteranumber(0-20):";cin>>num;result=factor(num,squ,cub);if(result==sucess){cout<<"num:"<<num<<endl;cout<<"squ:"<<squ<<endl;cout<<"cub:"<<cub<<endl;}elsecout<<"error"<<endl;return0;}err_codefactor(intn,int&rsqu,int&rcub){if(n>20)returnerror;else{rsqu=n*n;rcub=n*n*n;returnsucess;}}enteranumber(0-20):3num:3Squ:9Cub:27Cat&Function(){CatTom(5,9);returnTom;}//wrongDynamicMemoryManagementTheFreeStoreMemoryAllocationMemoryDeallocationCopyConstructorsSomeCommonPitfallsMemoryLeaksOverwritesUsingDeallocatedMemoryDeallocatingMemoryTwiceThefreestoreVariablescreatedinthefreestorehavedynamicextent.Theextentofavariabledescribeshowlongavariablestaysaroundinaprogram.Anothertermcommonlyusedinplaceofextentislifetime.MemoryAllocationTheprocessofobtainingmemoryfromthefreestoreiscalledmemoryallocation.TheoperatornewisusedinC++toallocatememorydynamically.Memory
AllocationObjectsMemoryDeallocationThedeleteoperatordeallocatesmemorythatisallocatedusingthenewoperator.#include<iostream>usingnamespacestd;intmain(){intvar=5;int*pLoc=&var;int*pHeap=newint;*pHeap=7;cout<<var<<endl;cout<<*pLoc<<endl;cout<<*pHeap<<endl;deletepHeap;//pHeap=0;pHeap=newint;*pHeap=9;cout<<*pHeap<<endl;deletepHeap;//pHeap=0;return0;}5579#include<iostream>usingnamespacestd;intmain(){int*pInt=newint;*pInt=10;cout<<*pInt<<endl;deletepInt;long*pLong=newlong;*pLong=0;cout<<*pLong<<endl;*pInt=20;//oh!cout<<*pInt<<endl;cout<<*pLong<<endl;deletepLong;return0;}1002020CopyConstructorsAcopyconstructordefinestheactionsthatneedtobetakentocreateacopyofanobject.Unlikeregularconstructors,aclasscancontainonlyonecopyconstructor.IfaC++classdoesnotdefineacopyconstructor,thelanguageprovidestotheclassadefaultcopyconstructor.Thisdefaultcopyconstructormakesabyte-by-bytecopyoftheobject.CopyConstructorsCopyconstructorsareinvokedwheneveracopyofanobjecthastobemade.Threesituationswhencopiesofobjectsaremade.DuringdeclarationthatinvolvesinitializationWhenobjectsarepassedbyvalueWhenobjectsarereturnedbyvalueExampleProblemanalysisOldobjectIt’smembervariablesNewobjectIt’smembervariables5FreestorageDefaultcopyconstructorOldobjectIt’smembervariablesNewobjectIt’smembervariables5FreestorageMissingpointerAnalysis:deepcopyOldobjectIt’smembervariablesNewobjectIt’smembervariables55FreestorageDeepcopyCopy
Constructorsshallowcopydeepcopy.SomeCommonPitfallsMemoryLeaksOverwritesUsingDeallocatedMemoryDeallocatingMemoryTwiceReturnMechanismsforCodeReuseandAbstractionInheritancePolymorphismTemplatesExceptionHandlingInheritanceInheritanceisamechanisminC++thatfacilitatesabstractionandcodereuse.Inheritanceestablishesthe"is-a"relationshipsbetweentheclassescontainedinaprogram.Usinginheritance,newclassescanbebuiltbasedonoldclasses,allowingchildclassestosharedatamembersandfunctionsoftheparentclass.Itisthroughtheserelationshipsthattheadvantagesofdataabstraction(generalizationandspecialization)emerge.ExampleC++InheritanceInheritanceC++andJavadifferslightlyinthedatamembersthatchildclassesinheritfromtheirparents.InC++,achildclassinheritsallnon-privatedatamembersincludingconstructors.AchildclassinJava,however,inheritsfromitsparentclassallnon-privatedatamembersexceptconstructors.Inbothlanguages,childclassesinheritallthenon-privatedatamembers.InC++,thisincludespublicandprotecteddatamembers.ExampleinheritanceC++containsthreetypes,orlevels,ofinheritance:public,usepublicinheritancetomodelthe"is-a"relationshipoftwoclasses.private,protectedmodeladifferenttypeofrelationship,namelythe"uses-a"relationship.
?#include<iostream>enumBREED{GOLDEN,CAIRN};usingnamespacestd;classmammal{public:mammal();~mammal();intgetage()const{returnage;}voidsetage(inti){age=i;}protected:intage;};classdog:publicmammal{public:dog();~dog();BREEDgetbreed()const{returnbreed;}voidsetbreed(BREEDb){breed=b;}protected:BREEDbreed;};mammal::mammal():age(1){cout<<"mammalconstructor"<<endl;}mammal::~mammal(){cout<<"mammaldestructor"<<endl;}dog::dog():breed(GOLDEN){cout<<"dogconstructor"<<endl;}dog::~dog(){cout<<"dogdestructor"<<endl;}intmain(){dogfido;cout<<"fidoageis"<<fido.getage()<<endl;return0;}mammalconstructordogconstructorfidoageis1dogdestructormammaldestructorMultipleinheritanceSub-classisderivedfrommultiplebaseclasses.Syntax
class<sub_class>:public<base_class1>,<base_class2> { … }ExampleHorseBirdPegasusProblemsofmultipleinheritanceConstructors?AlloftheconstructorofallbaseclassesAmbiguousfunctioncalling?Usingspecificdomain#include<iostream>enumCOLOR{GOLDEN,RED};usingnamespacestd;classhorse{public:horse(COLORc,intw):color(c),weight(w){cout<<"horseconstruction"<<endl;}~horse(){cout<<"horsedestruction"<<endl;}intgetweight()const{returnweight;}COLORgetcolor()const{returncolor;}voidsetweight(inti){weight=i;}protected:COLORcolor;intweight;};classbird{public:bird(COLORc,boolm):color(c),migrate(m){cout<<"birdconstruction"<<endl;}~bird(){cout<<"birddestruction"<<endl;}COLORgetcolor()const{returncolor;}voidsetcolor(COLORb){color=b;}protected:COLORcolor;boolmigrate;};classpegasus:publichorse,publicbird{public:pegasus(COLORc,intw,boolm,inth):horse(c,w),bird(c,m),height(h){cout<<"pegasusconstruction"<<endl;}~pegasus(){cout<<"pegasusdestruction"<<endl;}intgetheight()const{returnheight;}protected:intheight;};intmain(){pegasusp(RED,5,true,50);cout<<p.getheight()<<endl;
//cout<<p.getcolor()<<endl;return0;}horseconstructionbirdconstructionpegasusconstruction50pegasusdestructionbirddestructionhorsedestruction?Problems如果Animal中有個(gè)成員變量age和一個(gè)成員函數(shù)getage(),如果調(diào)用P.getage(),那么究竟是通過Horse還是通過Bird來調(diào)用從Animal中繼承的getage()方法?HorseBirdPegasusAnimalAnimalProblems…classpegasus:publicHorse,publicBird{public:pegasus(COLORc,intw,boolm,inth,inta):horse(c,h,a),bird(c,m,a),height(h){cout<<“pegasuaconstructor〞<<endl;}~pegasus(){cout<<“pegasusdestructor〞<<endl;}intgetage()const{returnHorse::getage();}intgetheight()const{returnheight;}private:height;}intmain(){pegasusp(RED,5,true,10,2);cout<<“pageis〞<<p.getage()<<endl;return0;}如果要在pegasus對象中調(diào)用getage()方法,就必須明確或完全限定這個(gè)方法。AnimalconstructorhorseconstructorAnimalconstructorbirdconstructorpegasusconstructorpageis2pegasusdestructorbirddestructoranimaldestructorhorsedestructoranimaldestructorVirtualinheritanceDiamondinheritance可以通過虛繼承的方法告知C++你不想使用共享基類的兩個(gè)副本,而只想共享一個(gè)基類HorseBirdPegasusAnimalVirtualinheritanceclassanimal{…};classhorse:virtualpublicanimal{…};classbird:virtualpublicanimal{…};classpegasus:publichorse,publicbird{…};intmain(){pegasusp(RED,5,true,10,2);cout<<“pageis〞<<p.getage()<<endl;return0;}Animalconstructorhorseconstructorbirdconstructorpegasusconstructorpageis2pegasusdestructorbirddestructorhorsedestructoranimaldestructor?PolymorphismAMechanismforAbstractionpolymorphismistheabilityofanobjecttotakeonseveraldifferentforms.Functionsoverridepolymorphismallowsaprogrammertorefertoanobjectofoneclassasanobjectofanotherclass.ClassinheritancePolymorphismFirst,wecancreatecollectionsofheterogeneousobjects.Wecanoperateontheindividualobjectsinthesecollectionsasiftheywereallofthesametype,withouttheobjectslosingtheirrealidentities.Account[]accounts={newCheckingAccount("Fred",500,100),newSavingsAccount("Wilma",1000,0.03),newCheckingAccount("Barney",200,100),newBondAccount("Betty",2000,0.07)};for(inti=0;i<4;++i){System.out.println(accounts[i].showBalance());}Listing1
PolymorphisminJava
PolymorphismSecond,wecancodealgorithmsthatmakeonlyminimalassumptionsabouttheobjectstheymanipulate.Thiscanallowanalgorithmtocontinuetofunctioncorrectlyevenwhenaprogrammerintroducesnewchildclassesintothesystem.FunctionsoverrideExampleTraditionalmethod
intDouble(int); longDouble(long); floatDouble(float); doubleDouble(double);Functionoverload
intDouble(int); longDouble(long); floatDouble(float); doubleDouble(double);當(dāng)派生類用與基類的成員函數(shù)相同的返回值和簽名,但卻用新的實(shí)現(xiàn)方法創(chuàng)立一個(gè)函數(shù)時(shí),就稱為覆蓋了該方法。其中簽名指的是函數(shù)名,參數(shù)表和可能的關(guān)鍵字const。#include<iostream>usingnamespacestd;classmammal{public:mammal():{cout<<"mammalconstructor"<<endl;}~mammal(){cout<<"mammaldestructor"<<endl;}voidspeak()const{cout<<"mammalsound"<<endl;}protected:intage;};classdog:publicmammal{public:dog(){cout<<"dogconstructor"<<endl;}~dog(){cout<<"dogdestructor"<<endl;}voidspeak()const{cout<<"dogsound"<<endl;}protected:intheight;};intmain(){mammalpig;dogfido;pig.speak();fido.speak();return0;}mammalconstructormammalconstructordogconstructormammalsounddogsounddogdestructormammaldestructormammaldestructor重載&覆蓋“overload(重載)〞:
overload方法時(shí)參數(shù)類型、個(gè)數(shù)、順序至少有一個(gè)不相同;不能overload只有返回值不同的方法名;
overload存在于父類和子類、同類中。
“override〔覆蓋〕〞
override時(shí),方法名、參數(shù)、返回值相同;
子類方法不能縮小父類方法的訪問權(quán)限;
子類方法不能拋出比父類方法更多的異常〔但子類方法可以不拋出異?!常?/p>
override存在于父類和子類之間。
隱藏基類方法#include<iostream>usingnamespacestd;classmammal{public:mammal():{cout<<"mammalconstructor"<<endl;}~mammal(){cout<<"mammaldestructor"<<endl;}voidspeak()const{cout<<"mammalsound"<<endl;}voidspeak(inti)const{cout<<"mammal"<<i<<"sound"<<endl;}protected:intage;};classdog:publicmammal{public:dog(){cout<<"dogconstructor"<<endl;}~dog(){cout<<"dogdestructor"<<endl;}voidspeak()const{cout<<"dogsound"<<endl;}protected:intheight;};intmain(){mammalpig;dogfido;pig.speak();pig.speak(2);fido.speak();//fido.speak(2);return0;}mammalconstructormammalconstructordogconstructormammalsoundmammal2sounddogsounddogdestructormammaldestructormammaldestructor?#include<iostream>usingnamespacestd;classmammal{public:mammal():{cout<<"mammalconstructor"<<endl;}~mammal(){cout<<"mammaldestructor"<<endl;}voidspeak()const{cout<<"mammalsound"<<endl;}voidspeak(inti)const{cout<<"mammal"<<i<<"sound"<<endl;}protected:intage;};classdog:publicmammal{public:dog(){cout<<"dogconstructor"<<endl;}~dog(){cout<<"dogdestructor"<<endl;}voidspeak()const{cout<<"dogsound"<<endl;}protected:intheight;};intmain(){mammalpig;dogfido;pig.speak();pig.speak(2);fido.speak();fido.mammal::speak(2);return0;}mammalconstructormammalconstructordogconstructormammalsoundmammal2sounddogsoundmammal2sounddogdestructormammaldestructormammaldestructor調(diào)用基方法PolymorphisminC++TheapproachtakentoachievethisgoalinC++isthesameasinJava.Programmersinvokeoverriddenmethodsofachildclassviaanancestorclass.InC++,weusevirtualfunctionsinconjunctionwithpointerstoaccessobjectspolymorphically.?Howtousepolymorphism??Solutionofpolymorphism-1usingvirtualfunctionsSolutionofpolymorphism-2WecouldalsohavemodifiedShapebymakingarea()notjustvirtualbutalsototally
undefined.Afunctionofthissortiscalledapurevirtualfunction.PurevirtualfunctionAclassthatcontainsapurevirtualfunctionisknownasanabstractclass.ImplementationsinC++onlyuseabstractclassesinconjunctionwithinheritance.programmersnevercreateinstancesofabstractclasses.merelytospecifythecommoninterfaceofchildclassesandtoaccessthesechildclassespolymorphically.Slicingproblem注意:虛
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年曝氣轉(zhuǎn)刷合作協(xié)議書
- 人教版八年級(jí)地理上冊聽課評課記錄《工業(yè)》
- 聽七年級(jí)英語評課記錄
- 人教版地理七年級(jí)下冊6.1《位置和范圍》(第1課時(shí))聽課評課記錄
- 招送水工合同(2篇)
- 犬舍加盟合同(2篇)
- 五年級(jí)數(shù)學(xué)下冊蘇教版第四單元第7課《分?jǐn)?shù)與小數(shù)互化》聽評課記錄
- 岳麓版歷史七年級(jí)下冊第24課《從貞觀之治到開元盛世》聽課評課記錄1
- 人民版道德與法治九年級(jí)上冊8.1《森林的砍伐 空氣污染》聽課評課記錄
- 湘教版數(shù)學(xué)七年級(jí)下冊《2.1.1同底冪的乘法》聽評課記錄
- 【課件】和爸爸騎馬遇野兔讀后續(xù)寫講評課課件
- 深交所證券法講義課件
- 降低一次性耗材漏收率品管圈課件
- 服裝標(biāo)準(zhǔn)流水生產(chǎn)線
- 質(zhì)量管理體系策劃-烏龜圖
- 2024年內(nèi)蒙古電力集團(tuán)招聘筆試參考題庫含答案解析
- 保潔服務(wù)品質(zhì)履約評估報(bào)告
- 火龍罐綜合灸療法
- 紅色中國風(fēng)西安旅游PPT模板
- 英語課堂游戲PPT-英語游戲4個(gè)PPT-(切西瓜-打地鼠-開火車-植物大戰(zhàn)僵尸)
- 皮內(nèi)注射技術(shù)操作考核評分標(biāo)準(zhǔn)
評論
0/150
提交評論