虚函数、抽象类(上课铃)
6-3 上课铃响之后 - C/C++ 多态
分数 20
作者 海洋饼干叔叔
单位 重庆大学
如本章开篇所述,当小学里的上课铃响之后,学生(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.
class Person
{
public:
virtual void bellRing()=0;
virtual ~Person(){}
};
class Student:public Person
{
public:
void bellRing()
{
cout<<"I am a student learning in classroom."<<endl;
}
~Student()
{
cout<<"A student object destroyed."<<endl;
}
};
class Teacher:public Person
{
public:
void bellRing()
{
cout<<"I am a teacher teaching in classroom."<<endl;
}
~Teacher()
{
cout<<"A teacher object destroyed."<<endl;
}
};
class Principal:public Person
{
public:
void bellRing()
{
cout<<"I am the principal inspecting in campus."<<endl;
}
~Principal()
{
cout<<"A principal object destroyed."<<endl;
}
};