C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch07】Polymorphism and Virtual Functions_第1頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch07】Polymorphism and Virtual Functions_第2頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch07】Polymorphism and Virtual Functions_第3頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch07】Polymorphism and Virtual Functions_第4頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch07】Polymorphism and Virtual Functions_第5頁
已閱讀5頁,還剩13頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

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(){//創(chuàng)建學生對象Studentstudent(\張三\1234567890,\三年級一班\10);//創(chuàng)建教師對象Teacherteacher(\李四\9876543210,\數(shù)學系\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<<\教師教學數(shù)量:\<<teacher.getTeachingQuantity()<<\節(jié)/周\<<endl;cout<<\教師工作時間:\<<teacher.calculateWorkTime()<<\小時/周\<<endl;return0;}```在這個程序中,`Person`類是學生和教師類的基類,包含姓名和身份證號兩個屬性。`Student`和`Teacher`類分別繼承于`Person`類,并新增了自己的屬性和方法。`Student`類有一個額外的屬性`className`表示班級,和`studyTime`表示每周學習時間。`calculateWorkTime`方法用于計算學生的工作時間,即學習時間乘以2。`Teacher`類有一個額外的屬性`department`表示部門,和`teachingQuantity`表示每周教學數(shù)量。`calculateWorkTime`方法用于計算教師的工作時間,即教學數(shù)量乘以2。在程序的`main`函數(shù)中,我們創(chuàng)建了一個學生對象和一個教師對象,并打印出他們的信息以及計算出的工作/學習時間。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類有級別、工資和工作時間的成員變量,以及計算支付和降級的成員函數(shù)。Manager類還有一個雇主成員變量,并重寫了計算支付的函數(shù)。Salesperson類還有銷售額成員變量,并也重寫了計算支付的函數(shù)。在主函數(shù)中,示例了如何創(chuàng)建員工、經理和銷售員對象,并調用它們的計算支付函數(shù)和降級函數(shù)。輸出會顯示出每個類的支付金額,以及員工降級后的級別。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函數(shù),用于返回格式化的類信息。Student類從Person類派生而來,并添加了一個名為studentID的新成員。在主函數(shù)中,我們創(chuàng)建了一個Person對象和一個Student對象,并分別輸出它們的類信息。運行該程序,你將得到類似以下的輸出結果:```Person:Name:John;地址:123MainSt.Student:Name:Alice;地址:456ElmSt.8.Writeaprogram.(1)AbstractbaseclassShape.(2)ClassesTriangle,SquareandCirclearederivedfromShape.(3)CalculatetheareasandperimetersofTriangle,SquareandCircle.下面是一個使用C++編寫的示例程序,實現(xiàn)了抽象基類Shape和派生類Triangle、Square和Circle的功能。每個形狀類都可以計算自身的面積和周長。請注意,代碼中的計算公式可能需要根據實際情況進行更改。```cpp#include<iostream>usingnamespacestd;//抽象的基類形狀classShape{public://純虛函數(shù),用于計算面積virtualfloatgetArea()=0;//純虛函數(shù),用于計算周長virtualfloatgetPerimeter()=0;};//類三角形,從形狀派生classTriangle:publicShape{private:floatbase;floatheight;public://構造函數(shù)Triangle(floatbase,floatheight){this->base=base;this->height=height;}//重寫計算面積的函數(shù)floatgetArea()override{return0.5*base*height;}//重寫計算周長的函數(shù)floatgetPerimeter()override{//假設三角形的邊長相等return3*base;}};//類方形,從形狀派生classSquare:publicShape{private:floatside;public://構造函數(shù)Square(floatside){this->side=side;}//重寫計算面積的函數(shù)floatgetArea()override{returnside*side;}//重寫計算周長的函數(shù)floatgetPerimeter(){return4*side;}};//類圓形,從形狀派生classCircle:publicShape{private:floatradius;constfloatpi=3.14159;//假設圓周率為3.14159public://構造函數(shù)Circle(floatradius){this->radiusradius;}//重寫計算面積的函數(shù)floatgetArea()override{returnpi*radius*radius;}//重寫計算周長的函數(shù)floatgetPerimeter()override{return2*pi*radius;}};intmain(){//創(chuàng)建三個形狀對象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。每個派生類實現(xiàn)了Shape基類中的純虛函數(shù)getArea()和getPerimeter(),并提供了自己的實現(xiàn)。在主函數(shù)中,我們創(chuàng)建了一個Triangle對象、一個Square對象和一個Circle對象,并使用它們的成員函數(shù)分別計算和輸出面積和周長。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;//虛擬函數(shù)打印};//二維形狀類classTwoDShape:publicShape{public:virtualfloatarea()=0;//虛擬函數(shù)計算面積virtualfloatperimeter()=0;//虛擬函數(shù)計算周長};//三維形狀類classThreeDShape:publicShape{public:virtualf

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論