已阅读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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 营销策划方案撰写与执行模板
- 2026年投资银行业务学习材料及考试大纲
- 企业人力资源结构分析与优化表
- 2026年客运值班员岗位考试题库
- 2026年酒店业人事主管面试题及答案
- 建设工程廉洁合同协议范本
- 现代生态农牧循环示范园规划与投资报告
- 2026年医美行业运营部经理考试题目与解答
- 2026年餐饮连锁企业厨师长的招聘与考核方法
- 2026年输血技师面试题集
- 道路清扫保洁重点路段分析及解决措施
- 民主建国会会史课件
- 鹦鹉热护理措施
- 员工劳务合同书
- 郑州市郑州外国语中学等4校2022-2023学年七年级上学期期末数学试题【带答案】
- 人体形态学(山东联盟)智慧树知到期末考试答案章节答案2024年青岛滨海学院
- 《办公用房租赁合同》范本标准版可打印
- 人机环管安全管理措施
- 大庆一中、六十九中初四上学期期末质量检测物理试题
- 小学生一、二、三年级家庭奖罚制度表
- 中图版地理七年级上册知识总结
评论
0/150
提交评论