SavCpp8PowerPointsSavitch_ch_15_第1页
SavCpp8PowerPointsSavitch_ch_15_第2页
SavCpp8PowerPointsSavitch_ch_15_第3页
SavCpp8PowerPointsSavitch_ch_15_第4页
SavCpp8PowerPointsSavitch_ch_15_第5页
已阅读5页,还剩72页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter15,Inheritance,Overview,15.1InheritanceBasics15.2InheritanceDetails15.3Polymorphism,Slide15-3,15.1,Inheritance,InheritanceBasics,Inheritanceistheprocessbywhichanewclass,calledaderivedclass,iscreatedfromanotherclass,calledthebaseclassAderivedclassautomaticallyhasallthemembervariablesandfunctionsofthebaseclassAderivedclasscanhaveadditionalmembervariablesand/ormemberfunctionsThederivedclassisachildofthebaseorparentclass,Slide15-5,EmployeeClasses,Todesignarecord-keepingprogramwithrecordsforsalariedandhourlyemployeesSalariedandhourlyemployeesbelongtoaclassofpeoplewhosharethepropertyemployeeAsubsetofemployeesarethosewithafixedwageAnothersubsetofemployeesearnhourlywagesAllemployeeshaveanameandSSNFunctionstomanipulatenameandSSNarethesameforhourlyandsalariedemployees,Slide15-6,ABaseClass,WewilldefineaclasscalledEmployeeforallemployeesTheEmployeeclasswillbeusedtodefineclassesforhourlyandsalariedemployeesAdefinitionoftheemployeeclassisfoundin,Slide15-7,Display15.1,Display15.2,Functionprint_check,Functionprint_checkwillhavedifferentdefinitionstoprintdifferentchecksforeachtypeofemployeeAnEmployeeobjectlackssufficientinformationtoprintacheckEachderivedclasswillhavesufficientinformationtoprintacheck,Slide15-8,ClassHourlyEmployee,HourlyEmployeeisderivedfromClassEmployeeHourlyEmployeeinheritsallmemberfunctionsandmembervariablesofEmployeeTheclassdefinitionbeginsclassHourlyEmployee:publicEmployee:publicEmployeeshowsthatHourlyEmployeeisderivedfromclassEmployeeHourlyEmployeedeclaresadditionalmembervariableswage_rateandhours,Slide15-9,Display15.3,InheritedMembers,AderivedclassinheritsallthemembersoftheparentclassThederivedclassdoesnotre-declareorre-definemembersinheritedfromtheparent,exceptThederivedclassre-declaresandre-definesmemberfunctionsoftheparentclassthatwillhaveadifferentdefinitioninthederivedclassThederivedclasscanaddmembervariablesandfunctions,Slide15-10,ImplementingaDerivedClass,AnymemberfunctionsaddedinthederivedclassaredefinedintheimplementationfileforthederivedclassDefinitionsarenotgivenforinheritedfunctionsthatarenottobechangedTheHourlyEmployeeclassisdefinedin,Slide15-11,Display15.5,ClassSalariedEmployee,TheclassSalariedEmployeeisalsoderivedfromEmployeeFunctionprint_checkisredefinedtohaveameaningspecifictosalariedemployeesSalariedEmployeeaddsamembervariablesalaryTheinterfaceforSalariedEmployeeisfoundincontainstheimplementation,Slide15-12,Display15.4,Display15.6(1-2),ParentandChildClasses,RecallthatachildclassautomaticallyhasallthemembersoftheparentclassTheparentclassisanancestorofthechildclassThechildclassisadescendentoftheparentclassTheparentclass(Employee)containsallthecodecommontothechildclassesYoudonothavetore-writethecodeforeachchild,Slide15-13,DerivedClassTypes,AnhourlyemployeeisanemployeeInC+,anobjectoftypeHourlyEmployeecanbeusedwhereanobjectoftypeEmployeecanbeusedAnobjectofaclasstypecanbeusedwhereveranyofitsancestorscanbeusedAnancestorcannotbeusedwhereveroneofitsdescendentscanbeused,Slide15-14,DerivedClassConstructors,AbaseclassconstructorisnotinheritedinaderivedclassThebaseclassconstructorcanbeinvokedbytheconstructorofthederivedclassTheconstructorofaderivedclassbeginsbyinvokingtheconstructorofthebaseclassintheinitializationsection:HourlyEmployee:HourlyEmployee:Employee(),wage_rate(0),hours()/nocodeneeded,Slide15-15,AnyEmployeeconstructorcouldbeinvoked,DefaultInitialization,Ifaderivedclassconstructordoesnotinvokeabaseclassconstructorexplicity,thebaseclassdefaultconstructorwillbeusedIfclassBisderivedfromclassAandclassCisderivedfromclassBWhenaobjectofclassCiscreatedThebaseclassAsconstructoristhefirstinvokedClassBsconstructorisinvokednextCsconstructorcompletesexecution,Slide15-16,PrivateisPrivate,Amembervariable(orfunction)thatisprivateintheparentclassisnotaccessibletothechildclassTheparentclassmemberfunctionsmustbeusedtoaccesstheprivatemembersoftheparentThiscodewouldbeillegal:voidHourlyEmployee:print_check()net_pay=hours*wage_rage;net_payisaprivatememberofEmployee!,Slide15-17,TheprotectedQualifier,protectedmembersofaclassappeartobeprivateoutsidetheclass,butareaccessiblebyderivedclassesIfmembervariablesname,net_pay,andssnarelistedasprotected(notprivate)intheEmployeeclass,thiscode,illegalonthepreviousslide,becomeslegal:HourlyEmployee:print_check()net_pay=hours*wage_rage;,Slide15-18,ProgrammingStyle,Usingprotectedmembersofaclassisaconveniencetofacilitatewritingthecodeofderivedclasses.ProtectedmembersarenotnecessaryDerivedclassescanusethepublicmethodsoftheirancestorclassestoaccessprivatemembersManyprogrammingauthoritiesconsideritbadstyletouseprotectedmembervariables,Slide15-19,RedefinitionofMemberFunctions,Whendefiningaderivedclass,onlylistthetheinheritedfunctionsthatyouwishtochangeforthederivedclassThefunctionisdeclaredintheclassdefinitionHourlyEmployeeandSalariedEmployeeeachhavetheirowndefinitionsofprint_checkdemonstratestheuseofthederivedclassesdefinedinearlierdisplays.,Slide15-20,Display15.7(1-2),RedefiningorOverloading,AfunctionredefinedinaderivedclasshasthesamenumberandtypeofparametersThederivedclasshasonlyonefunctionwiththesamenameasthebaseclassAnoverloadedfunctionhasadifferentnumberand/ortypeofparametersthanthebaseclassThederivedclasshastwofunctionswiththesamenameasthebaseclassOneisdefinedinthebaseclass,oneinthederivedclass,Slide15-21,FunctionSignatures,Afunctionsignatureisthefunctionsnamewiththesequenceoftypesintheparameterlist,notincludinganyconstorsally_h.Employee:print_check();,Slide15-23,Section15.1Conclusion,CanyouExplainwhythedeclarationforget_nameisnotpartofthedefinitionofSalariedEmployee?GiveadefinitionforaclassTitledEmployeederivedfromclassSalariedEmployeewithoneadditionalstringcalledtitle?Addtwomemberfunctionsget_titleandset_title.Itshouldredefineset_name.,Slide15-24,15.2,InheritanceDetails,InheritanceDetails,Somespecialfunctionsare,forallpracticalpurposes,notinheritedbyaderivedclassSomeofthespecialfunctionsthatarenoteffectivelyinheritedbyaderivedclassincludeDestructorsCopyconstructorsTheassignmentoperator,Slide15-26,CopyConstructorsandDerivedClasses,Ifacopyconstructorisnotdefinedinaderivedclass,C+willgenerateadefaultcopyconstructorThiscopyconstructorcopiesonlythecontentsofmembervariablesandwillnotworkwithpointersanddynamicvariablesThebaseclasscopyconstructorwillnotbeused,Slide15-27,Operator=andDerivedClasses,Ifabaseclasshasadefinedassignmentoperator=andthederivedclassdoesnot:C+willuseadefaultoperatorthatwillhavenothingtodowiththebaseclassassignmentoperator,Slide15-28,DestructorsandDerivedClasses,AdestructorisnotinheritedbyaderivedclassThederivedclassshoulddefineitsowndestructor,Slide15-29,TheAssignmentOperator,Inimplementinganoverloadedassignmentoperatorinaderivedclass:ItisnormaltousetheassignmentoperatorfromthebaseclassinthedefinitionofthederivedclasssassignmentoperatorRecallthattheassignmentoperatoriswrittenasamemberfunctionofaclass,Slide15-30,TheOperator=Implementation,Thiscodesegmentshowshowtobegintheimplementationofthe=operatorforaderivedclass:Derivedstringname;andclassDog:publicPetpublic:virtualvoidprint();stringbreed;,Slide15-48,ASlicedDogisaPet,C+allowsthefollowingassignments:=Tiny;vdog.breed=GreatDane;vpet=vdog;However,vpetwillloosethebreedmemberofvdogsinceanobjectofclassPethasnobreedmemberThiscodewouldbeillegal:coutprint();islegalandproduces:name:Tinybreed:GreatDane,Slide15-52,voidDog:print()coutname:nameendl;coutbreed:breedbreed=GreatDane;ppet=pdog;,Display15.12(1-2),UseVirtualFunctions,Thepreviousexample:ppet-print();workedbecauseprintwasdeclaredasavirtualfunctionThiscodewouldstillproduceanerror:coutnamebreed;,Slide15-53,Why?,ppet-breedisstillillegalbecauseppetisapointertoaPetobjectthathasnobreedmemberFunctionprint()wasdeclaredvirtualbyclassPetWhenthecomputerseesppet-print(),itchecksthevirtualtableforclassesPetandDogandfindsthatppetpointstoanobjectoftypeDogBecauseppetpointstoaDogobject,codeforDog:print()isused,Slide15-54,RememberTwoRules,Tohelpmakesenseofobjectorientedprogrammingwithdynamicvariables,remembertheserulesIfthedomaintypeofthepointerp_ancestorisabaseclassfortheforthedomaintypeofpointerp_descendant,thefollowingassignmentofpointersisallowedp_ancestor=p_descendant;andnodatamemberswillbelostAlthoughallthefieldsofthep_descendantarethere,virtualfunctionsarerequiredtoaccessthem,Slide15-55,VirtualCompilation,Whenusingvirtualfunctions,youwillhavetodefineeachvirtualfunctionbeforecompilingDeclarationisnolongersufficientEvenifyoudonotcallthevirtualfunctionyoumayseeerrormessage:undefinedreferencetoClass_Namevirtualtable,Slide15-56,VirtualDestructors,DestructorsshouldbemadevirtualConsiderBase*pBase=newDerived;deletepBase;IfthedestructorinBaseisvirtual,thedestructorforDerivedisinvokedaspBasepointstoaDerivedobject,returningDerivedmemberstothefreestoreTheDeriveddestructorinturncalls

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论