如本章开篇所述,当小学里的上课铃响之后,学生(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;
}
解题思路:虚函数重载,虚析构函数重载
class Person{
public:
virtual void bellRing(){}
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;
}
};