上课铃响以后 //多态性

如本章开篇所述,当小学里的上课铃响之后,学生(Student)、教师(Teacher)和校长(Principal)会对同一个消息表现出不同的行为。请设计Person、Student、Teacher以及Principal类,合理安排他们之间的继承关系并将所有类的bellRing()及析构函数设计为虚函数,使得下述代码可以正常执行并产生期望的执行结果。

裁判测试程序样例:

 
#include <iostream>
using namespace std;

//定义Person, Student, Teacher, Principal类

int main() {
    cout << "School bell rings..." << endl;
    Person* persons[3] = {new Student(),new Teacher(),new Principal()};
    persons[0]->bellRing();
    persons[1]->bellRing();
    persons[2]->bellRing();
    for (auto i=0;i<3;i++)
        delete persons[i];
    return 0;
}
 

输入样例:

 

输出样例:

School bell rings...
I am a student learning in classroom.
I am a teacher teaching in classroom.
I am the principal inspecting in campus.
A student object destroyed.
A teacher object destroyed.
A principal object destroyed.
 1 #include <iostream>
 2 using namespace std;
 3 
 4 //定义Person, Student, Teacher, Principal类
 5 
 6 int main() {
 7     cout << "School bell rings..." << endl;
 8     Person* persons[3] = {new Student(),new Teacher(),new Principal()};
 9     persons[0]->bellRing();
10     persons[1]->bellRing();
11     persons[2]->bellRing();
12     for (auto i=0;i<3;i++)
13         delete persons[i];
14     return 0;
15 }
16  

 

 
 1 class Person {
 2     public:
 3     virtual void bellRing()=0;
 4     virtual ~Person(){}
 5 };
 6 class Student:public Person{
 7     public:
 8     virtual void bellRing()
 9     {
10         cout<<"I am a student learning in classroom."<<endl;
11     }
12     virtual ~Student(){cout<<"A student object destroyed."<<endl;}
13 };
14 class Teacher:public Person{
15     public:
16     virtual void bellRing()
17     {
18         cout<<"I am a teacher teaching in classroom."<<endl;
19     }
20     virtual ~Teacher(){cout<<"A teacher object destroyed."<<endl;}
21 };
22 class Principal:public Person{
23     public:
24     virtual void bellRing()
25     {
26         cout<<"I am the principal inspecting in campus."<<endl;
27     }
28     virtual ~Principal(){cout<<"A principal object destroyed."<<endl;}
29 };

 

posted @ 2023-04-20 23:00  刘冰宇  阅读(108)  评论(0)    收藏  举报