如本章开篇所述,当小学里的上课铃响之后,学生(Student)、教师(Teacher)和校长(Principal)会对同一个消息表现出不同的行为。请设计Person、Student、Teacher以及Principal类,合理安排他们之间的继承关系并将所有类的bellRing()及析构函数设计为虚函数,使得下述代码可以正常执行并产生期望的执行结果。
#include<bits/stdc++.h>
using namespace std;
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 a principal inspecting in campus."
}
~Principal()
{
cout<<"A principal object destroyed."
}
};
int main()
{
cout<<"Shool 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 presons[i];
}
return 0;
}