C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch06】Iaheritance_第1页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch06】Iaheritance_第2页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch06】Iaheritance_第3页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch06】Iaheritance_第4页
C++面向对象程序设计双语教程(第3版)-参考答案 刘嘉敏 【ch06】Iaheritance_第5页
已阅读5页,还剩12页未读, 继续免费阅读

下载本文档

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

文档简介

Chapter6Inberitance1.Answerthefollowingquestions.(1)Ifabaseclasshasaconstructorwithparametersbutnodefaultvalues,thenderivedclassneedn'thaveaconstructorwithargumentsexplicitly.Trueorfalse.Iffalse,pleasegivereasons.(2)Ifabaseclassandaderivedclassbothincludeamemberfunctionwiththesamename,whichmemberfunctionwillbecalledbyanobjectofthederivedclass,assumingthescoperesolutionoperatorisnotused.(3)AssumeaDervclassthatisprivatelyderivedfromclassBase.AnobjectofclassDervlocatedinthemainfunctioncanaccessa.publicmembersofDerv.b.protectedmembersofDerv.c.privatemembersofDerv.d.publicmembersofBase.e.protectedmembersofBase.f.privatemembersofBase.(4)Aclasshierarchya.showsthesamerelationshipsasanorganizationchart.b.describes“hasa”relationships.C.describes“isakindof"relationships.d.showsthesamerelationshipsasafamilytree.(5)Supposethatthederivedclasshasamemberobjectofanotherclass.Inwhatsequenceisanobjectofthederivedclassconstructed?(6)Whatisthemeaningofinheritance?Whatisthedifferencebetweencompositionandimheritance?(7)Explainthedifferencebetweentheprivateandprotectedmembersofaclass.(8)Supposeabaseclassandaderivedclassbothdefineafunctionofthesamenameandaderivedclassobjectinvokesthefunction.Whatmethodiscalled?(9)Considerthefollowinginheritancehierarchy:(a)HowmanydatamembersdoesBhave?Writeoutthesedatamembers.(b)}WhichdatamembersinAareaccessedinB?(1)错误。如果基类有一个具有参数的构造函数且没有默认值,派生类必须通过显式参数传递来调用基类的构造函数。否则,派生类无法正确地初始化基类的成员。正确。如果一个基类和派生类都有一个同名的成员函数,并且我们使用派生类的对象来调用该函数时,派生类的成员函数优先被调用。这是因为派生类继承了基类的成员函数,并且派生类的成员函数具有更高的优先级。(3)在主函数中,类Derv的对象可以访问:a.Derv的公共成员。d.基类的公共成员。它们可以通过对象名称来访问,类名可选。但是,类Derv的对象无法直接访问受保护的Derv和基类成,以及Derv的私有成员和基类的受保护或私有成员。只有派生类内部才能直接访问受保护和私有成员。(4)a.显示与组织结构图相同的关系。这是指类层次结构中的父子关系,父类表示更泛化的概念,子类表示更具体的概念,类似于组织结构图中的上下级关系。b.描述了\hasa\关系。这是指类层次结构中的关联关系,一个类可以拥有另一个类的对象作为其成员变量,表示一个对象包含另一个对象,并且能够通过该关系进行访问。c.描述了\是一种\的关系。这是指类层次结构中的继承关系,子类是父类的特殊情况或者更具体的实现,表示一个类是另一个类的一种类型或者子集。d.显示了与家谱相同的关系。这是指类层次结构中的继承关系,类似于家谱中的祖先和后代关系,每个个体都有一个父类以及可能有多个子类或后代类。(5)如果派生类具有另一个类的成员对象,那么在构造派生类对象时,先构造基类对象,然后再构造成员对象。(6)继承是面向对象编程中的一个重要概念,它允许派生类继承基类的属性和方法。继承的意义在于代码的重用和结构的扩展。通过继承,我们可以避免重复编写相似的代码,同时使代码更加模块化和易于维护。组成力与继承力之间的区别在于他们实现代码重用的不同。组成是通过创建其他类的对象作为当前类的成员,可以根据需要选择不同的对象,实现灵活性。而继承则是通过派生类继承基类的属性和方法,强调共性和层级关系。(7)类中的私有成员和受保护成员都是访问权限控制的一种方式。私有成员只能在当前类中访问,不能被派生类或其他类访问。受保护成员可以在当前类和派生类中访问,但不能在其他类中访问。具体区别在于:-私有成员:</br>-只能在当前类的成员函数或友元函数中访问;-子类无法直接访问私有成员。-受保护成员:</br>-可在当前类的成员函数、友元函数和派生类的成员函数中访问;-子类可以通过继承方式访问受保护成员;-子类的对象无法直接访问受保护成员。总之,私有成员主要用于实现封装性,受保护成员主要用于实现继承性。当一个派生类对象调用一个同名函数时,会优先调用派生类中的函数。这是因为派生类会继承基类的函数,但是如果派生类有自己定义的同名函数,就会覆盖基类的函数,从而成为首选的调用方法。这个过程称为函数重写或函数覆盖。略。2.Fillintheblanksineachofthefollowing:(1)Anewclassinheritspropertiesfromanexistingclass.Sotherelationshipiscalled.Anewclasshasanobjectofanotherclassasitsmember.Sotherelationshipiscalled.Theyareallwaysofreusingexistingsoftwaretocreatenewsoftware.(2)Whenderivingaclassftomabaseclasswithpublicinheritance,publicmembersofthebaseclassbecome_________membersofthederivedclass,andprotectedmembersofthebaseclassbecomemembersofthederivedclass.partoftheclasscan'tbeaccessedbythederivedclass.(3)Thederivedclassisderivedfromoneexistingclass.Theexistingclassiscalled.Themembersofthebaseclasscannotbedirectlyaccessedbythederivedclass,buttheandmemberscanbeaccessedbythederivedclass.Wheninitializingtheobjectofadcrivedclass,theconstructoroftheisinvokedfirst.(4)Tobeaccessedfromamemberfunctionofthederivedclass,thedataorfunctionsinthebaseclassmustbepublicor.略。略。3.Findtheerror(S)ineachofthefollowingandexplainhowtocorrectit.略。4.Writetheoutputofthefollowingcodes.略。5.TheUMLdiagramofaclassstructureisshowninFigure6-14.(1)ExplaintherelationshipamongclassesPoint,LineandType.(2)Explainthemeaningsofoperators#,-,and+intheclassdiagram.(3)DefineclassLine.(Hint;Theclassonlycontainsthedeclarationsofallmemberfunctions.)(4)HowmanydatamembersdoesclassLinehave?Writeoutthem.(5)DefinetheconstructorofclassLine.(6)DefinefunctionDisplayinclassLine.(Hint:thefunctiondisplaysallinformationofdatamembersinclassLine.)(7)WritethemainfunctiontotestclassLine.(1)在UML图中,类用一个矩形框表示,矩形框内部包含类的名称。类之间的关系用连线表示,主要有聚合、关联、继承和依赖关系。-聚合关系用空心菱形和实线表示,表示类之间是包含关系,表示一个类有包含关系的另一个类的实例,但两者之间的生命周期可以是独立的。-关联关系用实线表示,表示类之间有关联,一个类可以引用另一个类的对象。-继承关系用一个箭头实线表示,表示类之间的继承关系,子类继承父类的属性和方法。-依赖关系用虚线箭头表示,表示一个类依赖于另一个类,即一个类的实现依赖于另一个类。(2)在类图中,操作符#、-和+的含义如下:-\表示protected访问修饰符,表示成员是受保护的,只能在类内部和子类中访问。-\表示private访问修饰符,表示成员是私有的,只能在类内部访问。-\表示public访问修饰符,表示成员是公开的,可以在类的任何地方访问。(3)类别行(AbstractClass)是指只包含成员函数声明而不包含实现的类。它是一种抽象的类,不能被实例化,只能被继承,用来表示一类对象的通用行为和属性。(4)类Line有多少个数据成员取决于图中的具体定义。在图6-14中没有展示Line类的具体成员,所以无法确定。(5)构造函数是用来创建对象并初始化对象成员的方法。根据具体需求,可以定义类Line的构造函数。(6)在类行中定义什么是不清楚的,请提供更多上下文描述。6.Dcesignandimplementamini-payrollsystemincludingthreedifferentpeople:Teacher,StudentandTeachAssistant.ThisclasshierarchyisdescribedgraphicallyinFigure6-15.(1)ClassPersonhasdatamembers:number,nameandmonthlysalaryandmemberfunctionstocalculatethemonthlysalaryandtodisplayallinformation.(2)ClassesTeacherandTeachAssistantbothhaveanotherdatamember-level.(3)Thecalculationofthemonthlysalaryisdefinedasfollows:TheTeacher'smonthlysalaryisdeterminedby50Yuanperworkinghourand1500Yuansubsidy.TheStudentgets300Yuansubsidypermonth;TheTeachAssistantisapart-timestudentandhasateacher'sbenefts.Thesalaryisthestudent'ssubsidy,plusanextrasalaryof10Yuanperworkinghour.首先,我们创建一个名为Personnel的基类,其中包含编号、姓名和月薪的数据成员。成员函数包括计算月薪和显示所有信息。```pythonclassPersonnel:def__init__(self,id,name,monthly_salary):self.id=id=nameself.monthly_salary=monthly_salarydefcalculate_monthly_salary(self):returnself.monthly_salarydefdisplay_info(self):print(\编号:\self.id)print(\姓名:\)print(\月薪:\self.calculate_monthly_salary())```接下来,我们创建一个名为Teacher的子类,它从Personnel派生。除了继承基类的数据成员和成员函数外,教师还有一个级别的数据成员。我们在这个子类中添加一个特殊的计算月薪的功能。```pythonclassTeacher(Personnel):def__init__(self,id,name,monthly_salary,level):super().__init__(id,name,monthly_salary)self.level=leveldefcalculate_monthly_salary(self):base_salary=super().calculate_monthly_salary()returnbase_salary+base_salary*(0.1*self.level)```最后,我们创建一个名为TeachingAssistant的子类,它从Personnel派生。与教师类似,助教也有一个级别的数据成员,并添加特定的月薪计算方式。```pythonclassTeachingAssistant(Personnel):def__init__(self,id,name,monthly_salary,level):super().__init__(id,name,monthly_salary)self.level=leveldefcalculate_monthly_salary(self):base_salary=super().calculate_monthly_salary()returnbase_salary+base_salary*(0.05*self.level)```现在,我们可以创建不同的教师、学生和教师助理的实例,并调用它们的成员函数来计算月薪和显示信息。```pythonteacher=Teacher(1,\张三\5000,3)teacher.display_info()assistant=TeachingAssistant(2,\李四\3000,2)assistant.display_info()```这样,我们就实现了一个基于类层次结构的迷你工资制度,其中包括教师、学生和教师助理。每个类都有自己特定的月薪计算方式,并且可以显示所有信息。你可以根据需要扩展该类层次结构,并添加其他功能。7.DeriveaclasscalledEmployee2fromtheEmployeeclassinthischapter.Thisnewclassshouldaddadoubletypedataitemcalledcompensation,andalsoanenumtypecalledperiodtoindicatewhethertheemployeeispaidhourly,weekly,ormonthly.YouwillderivetheManager,Scientist,andLaborerclassesfromEmployee2insteadofEmployee.However,notethatinmanycircumstancesitmightbemoreinthespiritofOOPtocreateaseparatebaseclasscalledCompensationandthreenewclassesManager2,Scientist2,andLaborer2,andusemultipleinheritancetoderivethesethreeclassesfromtheoriginalManager,Scientist,andLaborerclassesandfromCompensation.Inthisway,noneoftheoriginalclassesneedstobemodified.```pythonclassEmployee2:def__init__(self,name,age,compensation,payment_type):=nameself.age=agepensation=compensationself.payment_type=payment_typedefget_info(self):returnf\Name:{},Age:{self.age},Compensation:{pensation},PaymentType:{self.payment_type}\defcalculate_payment(self,hours_worked):ifself.payment_type==PaymentType.HOURLY:returnpensation*hours_workedelifself.payment_type==PaymentType.WEEKLY:returnpensationelifself.payment_type==PaymentType.MONTHLY:returnpensation/4#Assuming4weeksinamonthclassPaymentType(Enum):HOURLY=\Hourly\WEEKLY=\Weekly\MONTHLY=\Monthly\```上述代码定义了一个Employee2类,该类具有姓名(name)、年龄(age)、补偿(compensation)和支付类型(payment_type)等属性。在Employee2类中,我们还定义了一个calculate_payment方法,该方法接受hours_worked参数,并根据支付类型计算薪水。根据不同的支付类型,薪水计算方式可能不同。8.Writeaprogram..(1)DefineaVehicleclassthathasaconstructorwithparametersandprotecteddatamemberswheels(numberofwheels)andweight(weightofvehicle).(2)ClassCarisderivedfromVehicleprivatelyandcontainsthedatamemberpassenger_load(largestnumberofpassengers).(3)ClassTruckisderivedfromVehicleprivatelyandcontainsthedatamemberspassenger_load(largestnumberofpassengers)andpay_load(loadcapacity)(4)Testthethreeclassesbyusingthemainfunction.```cpp#include<iostream>#include<string>usingnamespacestd;classVehicle{protected:intwheels;floatweight;public:Vehicle(intw,floatwt):wheels(w),weight(wt){}voiddisplay(){cout<<\Wheels:\<<wheels<<endl;cout<<\Weight:\<<weight<<\kg\<<endl;}};classCar:publicVehicle{private:intpassenger_load;public:Car(intw,floatwt,intpl):Vehicle(w,wt),passenger_load(pl){}voiddisplay(){Vehicle::display();cout<<\PassengerLoad:\<<passenger_load<<\people\<<endl;}};classTruck:publicVehicle{private:intpassenger_load;floatpayload;public:Truck(intw,floatwt,intpl,floatpd):Vehicle(w,wt),passenger_load(pl),payload(pd){}voiddisplay(){Vehicle::display();cout<<\PassengerLoad:\<<passenger_load<<\people\<<endl;cout<<\Payload:\<<payload<<\kg\<<endl;}};intmain(){Carcar(4,1000.0,5);cout<<\CarDetails:\<<;car.display();cout<<endl;Trucktruck(8,5000.0,2,10000.0);cout<<\TruckDetails:\<<endl;truck.display();return0;}```这个程序定义了`Vehicle`(车辆)类、`Car`(轿车)类和`Truck`(卡车)类,它们分别代表不同类型的车辆。`Vehicle`类具有受保护的数据成员`wheels`(车轮数量)和`weight`(车辆重量),并包含一个构造函数。`Car`类派生自`Vehicle`类,并添加了一个私有数据成员`passenger_load`(最大乘客数),同时也有自己的构造函数和显示函数。`Truck`类也派生自`Vehicle`类,并在基类的基础上增加了私有数据成员`passenger_load`(最大乘客数)和`payload`(承载能力),同样有自己的构造函数和显示函数。在`main`函数中,我们创建了一个`Car`对象和一个`Truck`对象,并调用它们的`display`函数来显示车辆的详细信息。9.Writeaprogramtoimplementthemanagementofbookandmagazinesales.Therequirementsareasfollows:(1)Inputthesalesrecordsofbooksandmagazines.(2)Outputthenamesofbooksandmagazinesandtheirsalessituations.Ifthesituationisgood,thismeansthatthebooksalesaremorethan500Yuanmonthly,andthemagazinesalesmorethan2500Yuan;otherwisethesituationispoor.```pythonclassPublication:def__init__(self,name):=nameself.sales=[]defadd_sale(self,amount):self.sales.append(amount)defget_sales_summary(self):total_sales=sum(self.sales)sales_status=\情况较好\iftotal_sales>500else\情况较差\returnf\

温馨提示

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

评论

0/150

提交评论