C++面向对象程序设计双语教程(第3版)-参考答案【ch07】Polymorphism and Virtual Functions.docx
Chapter 7 PoIymorph i sm and Vi rtuaIFunct i ons1. Wr ite the output of the fol lowing program.class Shape public:v 7. v . < 1.1?:;:->:.; , 7 : ; ?:</, , ., * , . * ; :;static intnumber; :; ?:'.:;,;,、:.:double xCooriyCoord; 5 / :可二:;.;:.:;Shapc(0llbIe x,double y):xCoord(x),yCoord(y) ., _ *, ,' Z 'a . , , ifcout«,Shape,s constructor0 << endi; I -;: < virtual double AreaQ const ; ;: .; .三;1.;. ;:.:I ,、, , , . » . 、. > / , . , .» , , . ,* / ' V-: 1 coin<< "Shape's area is" .: ” :;、;;:return 0.0;, J 、 ' . :* , . / :. , .: . j. , , a ' '» (' a ( , ZHShapeO , . H .:. , ' . z , ,:.cout"Shape's destructor*« endl; :; : .工 . * * *manager. calculatePayment();salesperson. calculatePayment();employee, demote();return 0;这段代码定义了一个基类Employee,以及从该类派生的Manager和Salesperson类。 Employee类有级别、工资和工作时间的成员变量,以及计算支付和降级的成员函数。Manager 类还有一个雇主成员变量,并重写了计算支付的函数。Salesperson类还有销售额成员变量, 并也重写了计算支付的函数。在主函数中,示例了如何创建员工、经理和销售员对象,并调用它们的计算支付函数和 降级函数。输出会显示出每个类的支付金额,以及员工降级后的级别。6. Here i s a c I ass h i erarchy, shown i n Figure 7-5, to represent var i ous med i a objects:G i ven the def i n i t i on of the base cI ass Med i a:class Media . . : . . . . s *.1 *' , , < .r*- . . .- ,.:;:加谖泊.M丽阳等蕊举M二 virtual void priirtO = 0; . , , * /f . s * , . a . » . ,三;:virtual string id。三0; 三三, protected: ”m string t /. . . . .:; .*, .懑涔涔犊哨案第海浅落澎 .Figure 7-5 The hierarchy diagram of these media objects(1) Exp lain the cI ass re I at i onsh i p descr i bed i n the h i erarchy d i agram.(2) Def i ne the Book and Magaz i ne cI asses accord i ng to the h i erarchy d i agram. (Hint: The pr i nt funct i on of each cI ass d i spI ays a I I i nformat i on of data members. The i d funct i on of each cI ass returns a str i ng i dent i f i er that can i nd i cate the med i a feature. Th i s i dent i f i er cons i sts of data members of each cI ass)(3) Wr i te the ma i n funct i on to test the Book and Magaz i ne c I asses. (Hint: You must def ine a pointer to a Media object in the main function.)略。7. Des i gns a cI ass named Person and i ts der i ved cI asses named Student and EmpIoyee.Assume that the dec Iarat ion of the Person cI ass i s as fol lows:class Person public:Pcrson(string stfN, string strA): name(strN)? address(strA)virtual string toStringQ const;private:string name, address; / 9.一:J ;二':.:':, z -(1) Def i ne the toStr i ng funct i on i n the Person cI ass. The return i ng va I ue of the toStr i ng funct i on i s used to display the cI ass i nformat i on in the fol lowing format: Name: XXXX;Address: XXXXXXX.(2) Def i ne the Student cI ass der i ved from the Person cI ass. A student has a cI ass status (freshmen, sophomore, jun i or, or sen i or). Overr i de the toStr i ng funct i on i n the Student cI ass.(3) Def i ne the EmpIoyee cI ass der i ved from the Person cI ass. An empIoyee has an off i ce and a saI ary. Overr i de the toStr i ng funct i on i n the EmpIoyee cI ass.(4) Write a top I eve I funct i on with a parameter of Person type and wr i te the ma i n funct i on to test the Student and EmpIoyee cI asses.epp ttinclude <iostream> using namespace std;class Person protected:string name;string address;public:Person(string name = string address = this->name = name;this->address 二 address;string toStringO return Name: + name + ; 地址: + address + );class Student : public Person private:int studentID;public:Student(string name = string address = int studentID = 0) :Person(name, address) this->studentID = studentID;);int main () Person person(John 123 Main St Student student(Alice 456 Elm St 12345);cout << Person: << endl;cout << person. toStringO << endl;cout <<Student: << endl;cout << student. toStringO << endl;return 0;这段代码定义了一个名为'Person、的基类及其名为Student'的派生类。Person类有一 个toString函数,用于返回格式化的类信息。Student类从Person类派生而来,并添加了 一个名为studentID的新成员。在主函数中,我们创建了一个Person对象和一个Student对象,并分别输出它们的类 信息。运行该程序,你将得到类似以下的输出结果:Person:Name: John;地址:123 Main St.Student:Name: Alice;地址:456 Elm St.Wr ite a program.1712 3z(x /( z(Abstract base cI ass Shape.Classes Tr iangle, Square and Circle are der i ved from Shape.CaIcuI ate the areas and per imeters of Tr iangle, Square and Circle.下面是一个使用C+编写的示例程序,实现了抽象基类Shape和派生类Triangle、Square 和Circle的功能。每个形状类都可以计算自身的面积和周长。请注意,代码中的计算公式 可能需要根据实际情况进行更改。、CPPttinclude <iostream>using namespace std;/抽象的基类形状class Shape public:/纯虚函数,用于计算面积virtual float getAreaO = 0;/纯虚函数,用于计算周长virtual float getPerimeter()二 0;);/类三角形,从形状派生class Triangle : public Shape private:float base;float height;public:/构造函数Triangle(float base, float height) this->base = base;this->height = height;/重写计算面积的函数float getArea() override return 0. 5 * base * height;/重写计算周长的函数float getPerimeter() override /假设三角形的边长相等return 3 * base;);/类方形,从形状派生class Square : public Shape private:float side;public:/构造函数Square(float side) this->side = side;)/重写计算面积的函数float getAreaO override return side * side;/重写计算周长的函数float getPerimeter () return 4 * side;);/类圆形,从形状派生class Circle : public Shape private:float radius;const float pi = 3. 14159; / 假设圆周率为 3. 14159public:/构造函数Circle(float radius) this->radius radius;)/重写计算面积的函数 float getAreaO override return pi * radius * radius;/重写计算周长的函数float getPerimeter() override return 2 * pi * radius;);int main() /创建三个形状对象Triangle triangle(5, 8);Square square(4);Circle circle(3);/输出每个形状的面积和周长cout << Triangle: Area = << triangle. getAreaO << Perimeter = << triangle. getPerimeter () << endl;cout << Square: Area = << square. getAreaO << Perimeter = << square. getPerimeter () << endl;cout << Circle: Area = << circle. getAreaO << Perimeter = << circle. getPerimeter () << endl;return 0;这个程序定义了一个抽象基类Shape,以及派生类Triangle、Square和Circle。每个 派生类实现了 Shape基类中的纯虚函数getAreaO和getPerimeter (),并提供了自己的实 现。在主函数中,我们创建了一个Triangle对象、一个Square对象和一个Circle对象, 并使用它们的成员函数分别计算和输出面积和周长。9. Design a cI ass h i erarchy as foI Iows;(1) A base cI ass Shape with v i rtuaI funct i on print.(2) CI asses TwoDShape and ThreeDShape der i ved from Shape. T i voDShape has v i rtuaI funct i ons area and per imeter: ThreeDShape has v i rtuaI funct i on voIume.(3) CI asses Tr i angIe, Square and Circle are der i ved from TwoDShape.(4) Classes Cube, Cuboid and Sphere are der i ved from ThreeDShape.Overr i de the def i n i t i on of the print funct i on of each der i ved cI ass. Test the h i erarchy by us i ng the ma i n funct i on and a top-1 eve I funct i on with a pointer to cI ass Shape.cpp#include<iostream> using namespace std;/基类形状class Shape public:virtual void print() = 0; / 虚拟函数打印 );/二维形状类class TwoDShape : public Shape public:virtual float area()=0; /虚拟函数计算面积virtual float perimeter() = 0; / 虚拟函数计算周长 ;/三维形状类class ThreeDShape : public Shape public:virtual float volume() = 0; / 虚拟函数计算体积 );/三角形类class Triangle : public TwoDShape public:void print () cout << This is a triangle. << endl; float area() /计算三角形的面积)float perimeter() /计算三角形的周长);/方形类class Square : public TwoDShape public:void print () cout << This is a square. << endl;float area() /计算方形的面积)float perimeter() /计算方形的周长);/圆形类class Circle : public TwoDShape public:void print () cout << This is a circle. << endl;)float area () /计算圆形的面积)float perimeter () /计算圆形的周长);/立方体类class Cube : public ThreeDShape public:void print () cout << This is a cube. << endl;)float volume () /计算立方体的体积);/圆柱体类class Cylinder : public ThreeDShape public:void print () cout << This is a cylinder. << endl;float volume () /计算圆柱体的体积);/球体类class Sphere : public ThreeDShape public:void print () cout << This is a sphere. << endl;float volume () 计算球体的体积上述代码中,每个类都继承自其对应的父类,并实现了虚拟函数。基类'Shape'中定义 了纯虚拟函数'print' ,而'TwoDShape'和'ThreeDShape'分别定义了纯虚拟函数'area'、 perimeter'volume' o子类 Triangle'、'Square'和 Circle'继承自 TwoDShape',分别 实现了面积和周长的计算方法;子类 Cube'、' Cylinder'和' Sphere'继承自ThreeDShape' , 分别实现了体积的计算方法。class Circle:public Shapepublic:Circle(double x,double y):Shape(x,y)( . cout« ”Circle's constructor11« cndl;. . number i-b;virtual double Area。const : :. .:cout«/'Circled area isw;.return 3.14*xCoord*xCoord; 一 Circled., , . . . , , , a a , * * «« , , . .cou(« "Circle's destructor" vv endl; .'': J -:;:" :一class Rcctangle;public Shape , , , , > : ., public:,.Rectangle(doublc x.double y):Shape(x5y)一:cout«,rRectanglers constructor1' « endl; numberH",J.-virtual double Area。const .cout«'Rectangle's area is”;return xCoord*yCoord;) . , :/Rectangle() , . . . , ,cout« ”Rectangles destructor*1« endl;: :; :. :二.;. .:3.;:;: : . .-void fun(const Shape &sp) ,二.X. . . e , :, , ., . .,.:cout« sp AreaQ « endl;. « int Shape: znumber 0;:、 . , . ., in£ TRsi)0-. - . / '' . -. , . , , . C. . . ;:. Circle c(2.0,5.0);.Rectangle r(2.0,4.0);cout« c.mmiber << endl;. cout« r.number« eadl; 一 ;:: 二二:丁.二: ;:二;二<: : m;.:,:":;:.丁丁:3 ;:.:.三二二:工工,二一 略。2. Wr ite the output of the fol lowing program.classA:二P同c: .aa ,;AU . :. . , _ . . . 9 . : cout << vi from A is ” << i« endl; ;:* * J . , . . . , , . , .:'七二;.;.;三:上:. ;:.;void tn-. . z .: /.;< sctI(20); 旌 * * * * * * » * * * * * , , . , , . , , fvirtual void setl(int m), tout« "Set a value in Class An *;i = 2 Am; . « , . . , . * *jwotected::.inti;-.);二二二二一,二: , . class B: public A ; , .* * j 'e " , * ' , ' .:. ,. , ' , ,., , . . 一 _ _ . ' public: , * . * . <, , * , J * e , , , . . . . .K., ._. , , , .:cout« ”i from B is :'«i << etidl;: . , , , . . . , . . . . . . . , . . . . . J virtual void sefl(int m):】 : cout «”Set a value in Class Bn h;:;:1 3 * m; .:; . * . : 、. ; ,intmainO . . ' / . . . . > . . , , , , . . , . .A* new BO; , . , , , , r , ., . 、Z: ;. :. ? : . /.:.z/. 略。3. G i ven the def i n i t i on of a Person cI ass as foI Iows:class Person=;。匚;mm-Hm七;tpublic:. ,. Jt , < . . . - . . : , Person(sttingn; inti):name(n), id(i)virtual int Tnne0 = 0;/A person spends time doing something.virtual void print。 cout« name «id « endl; pnvate:二:::二;.三,士二;丫;:;:三,二:,上:w.,:二 w:二 m二:,.:.:二;,二:二:匚:.:;二:.;:.:;:三;:二二;:彳上;:;.string name;int id;:二:二七三:-二 m;:;.:.,:.: : :;: ;,;丁:八":.: J:'.;:二:/;二:).:“: :.:,.: ;:/*:; ::二:3:,;::,;一:.:,:;:::;:二":!:;:;:,* * . * * * * * * * * , J" *" a" " * * * * ' , , «, » , , ( * * ;: * * * * . , * * _ , J9 .Des i gn the two c I asses Student and Teacher. They are der i ved from c I ass Person.(1) CI ass Student has the propert i es of name, i d, cIassNo and studyT ime per week;CI ass Teacher has the propert i es of name, i d, department and workT ime per week.(2) CaIcuI ate the work/student time. CaIcuI at i ng methods are def i ned as fol lows:The study time of a student i s the c I ass quantity multipl ied by 2 (hour) per week;The work time of a teacher i s the teach i ng quant i ty mu 11 i p I ied 2 (hour) per week.(3) Display the i nformat i on for cI asses Student and Teacher.、 、 、cppttinclude <iostream> ttinclude <string>using namespace std;class Person protected:string name;long id;public:Person (string name, long id) : name( name), id (_id) string getName() const return name; long getld() const return id; ;class Student : public Person private:string className;int studyTime;public:Student (string _name, long _id, string _className, int _studyTime) :Person( name, _id), className(_className), studyTime(_studyTime) ()int getStudyTime() const return studyTime; int calculateWorkTime() const return studyTime * 2; 计算学生的学 习时间;class Teacher : public Person private:string department;int teachingQuantity;public:Teacher(string name, long _id, string department, int _teachingQuantity):Person(_name,_id),department(_department),teachingQuantity QteachingQuantity) int getTeachingQuantity() const return teachingQuantity; int calculateWorkTime() const return teachingQuantity * 2; / 计算 教师的工作时间);int main () /创建学生对象Student student (、张三 1234567890, '三年级一班 10);/创建教师对象Teacher teacher (、李四、9876543210, '数学系、5);/输出学生和教师的信息cout << '学生姓名: << student. getNameO << endl;cout << '学生身份证: << student, getld () << endl;cout <<、学生班级: << student. getClassName () << endl;cout << '学生学习时间: << student. getStudyTime () << 小时/周、<< endl;cout << '学生工作时间: << student. calculateWorkTime () << 小时/周 << endl;cout << endl;cout <<、教师姓名: << teacher. getName () << endl;cout << '教师身份证: << teacher, getld () << endl;cout <<、教师部门: << teacher. getDepartment () << endl;cout << '教师教学数量: << teacher. getTeachingQuantity () << 节/周 << endl;cout << '教师工作时间: << teacher. calculateWorkTime () <<