版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter7PolymorphismandVirtualFunctions1.Writetheoutputofthefollowingprogram.略。2.Writetheoutputofthefollowingprogram.略。3.GiventhedefinitionofaPersonclassasfollows:DesignthetwoclassesStudentandTeacher.TheyarederivedfromclassPerson.(1)ClassStudenthasthepropertiesofname,id,classNoandstudyTimeperweek;ClassTeacherhasthepropertiesofname,id,departmentandworkTimeperweek.(2)Calculatethework/studenttime.Calculatingmethodsaredefinedasfollows:Thestudytimeofastudentistheclassquantitymultipliedby2(hour)perweek;Theworktimeofateacheristheteachingquantitymultiplied2(hour)perweek.(3)DisplaytheinformationforclassesStudentandTeacher.```cpp#include<iostream>#include<string>usingnamespacestd;classPerson{protected:stringname;longid;public:Person(string_name,long_id):name(_name),id(_id){}stringgetName()const{returnname;}longgetId()const{returnid;}};classStudent:publicPerson{private:stringclassName;intstudyTime;public:Student(string_name,long_id,string_className,int_studyTime):Person(_name,_id),className(_className),studyTime(_studyTime){}intgetStudyTime()const{returnstudyTime;}intcalculateWorkTime()const{returnstudyTime*2;}//计算学生的学习时间};classTeacher:publicPerson{private:stringdepartment;intteachingQuantity;public:Teacher(string_name,long_id,string_department,int_teachingQuantity):Person(_name,_id),department(_department),teachingQuantity(_teachingQuantity){}intgetTeachingQuantity()const{returnteachingQuantity;}intcalculateWorkTime()const{returnteachingQuantity*2;}//计算教师的工作时间};intmain(){//创建学生对象Studentstudent(\张三\1234567890,\三年级一班\10);//创建教师对象Teacherteacher(\李四\9876543210,\数学系\5);//输出学生和教师的信息cout<<\学生姓名:\<<student.getName()<<endl;cout<<\学生身份证:\<<student.getId()<<endl;cout<<\学生班级:\<<student.getClassName()<<endl;cout<<\学生学习时间:\<<student.getStudyTime()<<\小时/周\<<endl;cout<<\学生工作时间:\<<student.calculateWorkTime()<<\小时/周\<<endl;cout<<endl;cout<<\教师姓名:\<<teacher.getName()<<endl;cout<<\教师身份证:\<<teacher.getId()<<endl;cout<<\教师部门:\<<teacher.getDepartment()<<endl;cout<<\教师教学数量:\<<teacher.getTeachingQuantity()<<\节/周\<<endl;cout<<\教师工作时间:\<<teacher.calculateWorkTime()<<\小时/周\<<endl;return0;}```在这个程序中,`Person`类是学生和教师类的基类,包含姓名和身份证号两个属性。`Student`和`Teacher`类分别继承于`Person`类,并新增了自己的属性和方法。`Student`类有一个额外的属性`className`表示班级,和`studyTime`表示每周学习时间。`calculateWorkTime`方法用于计算学生的工作时间,即学习时间乘以2。`Teacher`类有一个额外的属性`department`表示部门,和`teachingQuantity`表示每周教学数量。`calculateWorkTime`方法用于计算教师的工作时间,即教学数量乘以2。在程序的`main`函数中,我们创建了一个学生对象和一个教师对象,并打印出他们的信息以及计算出的工作/学习时间。4.GiventhedefinitionofclassPointasfollows:DesignaCircleclasswiththepropertiesofacenterandaradius.Thecenterofthecirclcisapoint.TheCircleclassmustbederivedfromthePointclass.TheCircleclasscanimplementtheoperationsofcalculatingtheareaandprintingoutthecenter,radiusandarea.DesignanotherclassCylinderwiththepropertiesofabaseandaheight.Thebaseisacircle.DerivethisclassfromtheCircleclass.TheCylinderclasscanimplementtheoperationsofcalculatingthevolume,andprintingoutthebase,heightandvolume.Supposethefollowingcodeisinthemainfunction.```pythonimportmathclassPoint:def__init__(self,x=0,y=0):self.x=xself.y=yclassCircle(Point):def__init__(self,center,radius):super().__init__(center.x,center.y)self.radius=radiusdefarea(self):returnmath.pi*self.radius**2defprint_details(self):print(\CircleDetails:\print(\Center:({},{})\format(self.x,self.y))print(\Radius:{}\format(self.radius))print(\Area:{:.2f}\format(self.area()))classCylinder(Circle):def__init__(self,base_center,radius,height):super().__init__(base_center,radius)self.height=heightdefvolume(self):returnself.area()*self.heightdefprint_details(self):print(\CylinderDetails:\print(\BaseCenter:({},{})\format(self.x,self.y))print(\Radius:{}\format(self.radius))print(\Height:{}\format(self.height))print(\Volume:{:.2f}\format(self.volume()))#Exampleusage:if__name__=='__main__':c=Circle(Point(0,0),3)c.print_details()print()cy=Cylinder(Point(2,2),3,5)cy.print_details()```Thiscodedefinesa`Point`classasthebaseclass,`Circle`classderivedfrom`Point`,and`Cylinder`classderivedfrom`Circle`.The`Circle`classcalculatestheareaandprintsthedetailsofacircle,whilethe`Cylinder`classcalculatesthevolumeandprintsthedetailsofacylinder.The`main`functiondemonstratestheusageoftheseclassesbycreatingobjectsandcallingtheirrespectivemethods.5.Giventhefollowingcode:(1)CompletethedefmitionofclassEmployee.Note:employee'spayment=payRate*hoursWorked.(2)DefimeaManagerclassderivedfromclassEmployee.IthasthemembersofEmploveeanditsownmemberlevel.Note:manager'spayment=payRate*level*hoursWorked.(3)DefineanotherclassSalesmanderivedfromclassEmployee.ItalsohasthemembersofEmployee,inadditiontoitsownmembersale.Note:salesman'spayment=payRate*sale*hoursWorked.(4)TesttheManagerandSalesmanclassesbyusingabaseclasspointer.```cpp#include<iostream>usingnamespacestd;classEmployee{protected:intlevel;floatsalary;intworkHours;public:Employee(intl,floats,inth):level(l),salary(s),workHours(h){}virtualvoidcalculatePayment(){floatpayment=salary*workHours;cout<<\Employee'spayment:$\<<payment<<endl;}voiddemote(){if(level>1){level--;}cout<<\Employee'sleveldemotedto:\<<level<<endl;}};classManager:publicEmployee{private:stringemployer;public:Manager(intl,floats,inth,stringe):Employee(l,s,h),employer(e){}voidcalculatePayment(){floatpayment=salary*level*workHours;cout<<\Manager'spayment:$\<<payment<<endl;}};classSalesperson:publicEmployee{private:intsales;public:Salesperson(intl,floats,inth,intsa):Employee(l,s,h),sales(sa){}voidcalculatePayment(){floatpayment=salary*workHours+sales*0.1;cout<<\Salesperson'spayment:$\<<payment<<endl;}};intmain(){Employeeemployee(3,20,8);Managermanager(5,30,8,\ABCCompany\Salespersonsalesperson(3,15,8,1000);employee.calculatePayment();manager.calculatePayment();salesperson.calculatePayment();employee.demote();return0;}```这段代码定义了一个基类Employee,以及从该类派生的Manager和Salesperson类。Employee类有级别、工资和工作时间的成员变量,以及计算支付和降级的成员函数。Manager类还有一个雇主成员变量,并重写了计算支付的函数。Salesperson类还有销售额成员变量,并也重写了计算支付的函数。在主函数中,示例了如何创建员工、经理和销售员对象,并调用它们的计算支付函数和降级函数。输出会显示出每个类的支付金额,以及员工降级后的级别。6.Hereisaclasshierarchy,showninFigure7-5,torepresentvariousmediaobjects:GiventhedefinitionofthebaseclassMedia:(1)Explaintheclassrelationshipdescribedinthehierarchydiagram.(2)DefinetheBookandMagazineclassesaccordingtothehierarchydiagram.(Hint:Theprintfunctionofeachclassdisplaysallinformationofdatamembers.Theidfunctionofeachclassreturnsastringidentifierthatcanindicatethemediafeature.Thisidentifierconsistsofdatamembersofeachclass)(3)WritethemainfunctiontotesttheBookandMagazineclasses.(Hint:YoumustdefineapointertoaMediaobjectinthemainfunction.)略。7.DesignsaclassnamedPersonanditsderivedclassesnamedStudentandEmployee.AssumethatthedeclarationofthePersonclassisasfollows:(1)DefinethetoStringfunctioninthePersonclass.ThereturningvalueofthetoStringfunctionisusedtodisplaytheclassinformationinthefollowingformat:Name:XXXX;Address:XXXXXXX.(2)DefinetheStudentclassderivedfromthePersonclass.Astudenthasaclassstatus(freshmen,sophomore,junior,orsenior).OverridethetoStringfunctionintheStudentclass.(3)DefinetheEmployeeclassderivedfromthePersonclass.Anemployeehasanofficeandasalary.OverridethetoStringfunctionintheEmployeeclass.(4)WriteatoplevelfunctionwithaparameterofPersontypeandwritethemainfunctiontotesttheStudentandEmployeeclasses.```cpp#include<iostream>usingnamespacestd;classPerson{protected:stringname;stringaddress;public:Person(stringname=\stringaddress=\{this->name=name;this->address=address;}stringtoString(){return\Name:\+name+\;\地址:\+address+\}};classStudent:publicPerson{private:intstudentID;public:Student(stringname=\stringaddress=\intstudentID=0):Person(name,address){this->studentID=studentID;}};intmain(){Personperson(\John\\123MainSt\Studentstudent(\Alice\\456ElmSt\12345);cout<<\Person:\<<endl;cout<<person.toString()<<endl;cout<<Student:\<<endl;cout<<student.toString()<<endl;return0;}```这段代码定义了一个名为\Person\的基类及其名为\Student\的派生类。Person类有一个toString函数,用于返回格式化的类信息。Student类从Person类派生而来,并添加了一个名为studentID的新成员。在主函数中,我们创建了一个Person对象和一个Student对象,并分别输出它们的类信息。运行该程序,你将得到类似以下的输出结果:```Person:Name:John;地址:123MainSt.Student:Name:Alice;地址:456ElmSt.8.Writeaprogram.(1)AbstractbaseclassShape.(2)ClassesTriangle,SquareandCirclearederivedfromShape.(3)CalculatetheareasandperimetersofTriangle,SquareandCircle.下面是一个使用C++编写的示例程序,实现了抽象基类Shape和派生类Triangle、Square和Circle的功能。每个形状类都可以计算自身的面积和周长。请注意,代码中的计算公式可能需要根据实际情况进行更改。```cpp#include<iostream>usingnamespacestd;//抽象的基类形状classShape{public://纯虚函数,用于计算面积virtualfloatgetArea()=0;//纯虚函数,用于计算周长virtualfloatgetPerimeter()=0;};//类三角形,从形状派生classTriangle:publicShape{private:floatbase;floatheight;public://构造函数Triangle(floatbase,floatheight){this->base=base;this->height=height;}//重写计算面积的函数floatgetArea()override{return0.5*base*height;}//重写计算周长的函数floatgetPerimeter()override{//假设三角形的边长相等return3*base;}};//类方形,从形状派生classSquare:publicShape{private:floatside;public://构造函数Square(floatside){this->side=side;}//重写计算面积的函数floatgetArea()override{returnside*side;}//重写计算周长的函数floatgetPerimeter(){return4*side;}};//类圆形,从形状派生classCircle:publicShape{private:floatradius;constfloatpi=3.14159;//假设圆周率为3.14159public://构造函数Circle(floatradius){this->radiusradius;}//重写计算面积的函数floatgetArea()override{returnpi*radius*radius;}//重写计算周长的函数floatgetPerimeter()override{return2*pi*radius;}};intmain(){//创建三个形状对象Triangletriangle(5,8);Squaresquare(4);Circlecircle(3);//输出每个形状的面积和周长cout<<\Triangle:Area=\<<triangle.getArea()<<\Perimeter=\<<triangle.getPerimeter()<<endl;cout<<\Square:Area=\<<square.getArea()<<\Perimeter=\<<square.getPerimeter()<<endl;cout<<\Circle:Area=\<<circle.getArea()<<\Perimeter=\<<circle.getPerimeter()<<endl;return0;}```这个程序定义了一个抽象基类Shape,以及派生类Triangle、Square和Circle。每个派生类实现了Shape基类中的纯虚函数getArea()和getPerimeter(),并提供了自己的实现。在主函数中,我们创建了一个Triangle对象、一个Square对象和一个Circle对象,并使用它们的成员函数分别计算和输出面积和周长。9.Designaclasshierarchyasfollows;(1)AbaseclassShapewithvirtualfunctionprint.(2)ClassesTwoDShapeandThreeDShapederivedfromShape.TivoDShapehasvirtualfunctionsareaandperimeter:ThreeDShapehasvirtualfunctionvolume.(3)ClassesTriangle,SquareandCirclearederivedfromTwoDShape.(4)ClassesCube,CuboidandSpherearederivedfromThreeDShape.Overridethedefinitionoftheprintfunctionofeachderivedclass.Testthehierarchybyusingthemainfunctionandatop-levelfunctionwithapointertoclassShape.```cpp#include<iostream>usingnamespacestd;//基类形状classShape{public:virtualvoidprint()=0;//虚拟函数打印};//二维形状类classTwoDShape:publicShape{public:virtualfloatarea()=0;//虚拟函数计算面积virtualfloatperimeter()=0;//虚拟函数计算周长};//三维形状类classThreeDShape:publicShape{public:virtualf
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026一例甲状腺癌术后并发神经损伤患者的护理案例培训课件
- 绢纺精炼操作工改进考核试卷含答案
- 塑料层压工岗前诚信考核试卷含答案
- 景泰蓝制作工创新实践评优考核试卷含答案
- 异丙醇装置操作工岗前技术应用考核试卷含答案
- 医学26年:脂肪肝诊疗进展解读 查房课件
- 26年应急处理能力评估
- 历史学博士生学术研讨会-促进学术交流和共同进步
- 2026 减脂期肉类挑选技巧课件
- 2026 减脂期煮肉课件
- 2026届江苏省苏北七市高三三模英语试题(含答案和音频)
- 资阳产业投资集团有限公司第三轮一般员工市场化招聘笔试历年难易错考点试卷带答案解析
- 2026年国有企业领导人员廉洁从业若干规定题库
- 2026厦门中考生物知识点背诵清单练习含答案
- 天然气工程质量监理工作总结
- 环保设施安全风险
- 2026年太原初一信息技术试卷
- 教育信息化领域违纪违规案例警示剖析材料
- 国开2026年春季《形势与政策》大作业答案
- 《毛泽东思想和中国特色社会主义》课件-专题一 马克思主义中国化时代化
- 2025年中国民用航空飞行学院马克思主义基本原理概论期末考试模拟题带答案解析
评论
0/150
提交评论