版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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内嵌函数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中有个成员变量age和一个成员函数getage(),如果调用P.getage(),那么究竟是通过Horse还是通过Bird来调用从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对象中调用getage()方法,就必须明确或完全限定这个方法。AnimalconstructorhorseconstructorAnimalconstructorbirdconstructorpegasusconstructorpageis2pegasusdestructorbirddestructoranimaldestructorhorsedestructoranimaldestructorVirtualinheritanceDiamondinheritance可以通过虚继承的方法告知C++你不想使用共享基类的两个副本,而只想共享一个基类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);当派生类用与基类的成员函数相同的返回值和签名,但却用新的实现方法创立一个函数时,就称为覆盖了该方法。其中签名指的是函数名,参数表和可能的关键字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方法时参数类型、个数、顺序至少有一个不相同;不能overload只有返回值不同的方法名;
overload存在于父类和子类、同类中。
“override〔覆盖〕〞
override时,方法名、参数、返回值相同;
子类方法不能缩小父类方法的访问权限;
子类方法不能抛出比父类方法更多的异常〔但子类方法可以不抛出异常〕;
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调用基方法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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 智能家居设备技术规范解读
- 2026年物联网工程师技能测试题目
- 2026年会计职称考试会计实务与经济法考点解析集
- 2026年管理学经典案例分析题集及解答
- 2026年心理学基础与应用心理咨询师专业能力测试题库
- 心衰患者活动指导与监测
- 2026年国际旅游与酒店营销策略测试题
- 2026年市场营销专业消费者行为分析考试题库
- 2026年外语专业八级考试跨文化交际与语言应用综合题
- 2026年操作系统使用与维护实践题目集
- 危险化学品安全法解读
- 广东省佛山市南海区2025-2026学年上学期期末八年级数学试卷(含答案)
- 放射应急演练及培训制度
- 储能技术培训课件模板
- 2026年烟台工程职业技术学院单招综合素质考试参考题库附答案详解
- IT项目管理-项目管理计划
- GB/T 7714-2025信息与文献参考文献著录规则
- 2026元旦主题班会:马年猜猜乐新春祝福版 教学课件
- 光伏收购合同范本
- 2025海洋水下机器人控制系统行业市场需求及发展趋势分析投资评估规划报告
- 物流金融管理培训课件
评论
0/150
提交评论