如本章开篇所述,当小学里的上课铃响之后,学生(Student)、教师(Teacher)和校长(Principal)会对同一个消息表现出不同的行为。请设计Person、Student、Teacher以及Principal类,合理安排他们之间的继承关系并将所有类的bellRing()及析构函数设计为虚函数,使得下述代码可以正常执行并产生期望的执行结果。
时间: 2023-06-18 18:07:26 浏览: 213
```C++
#include<iostream>
using namespace std;
class Person {
public:
virtual void bellRing() {
cout << "Person is walking towards the classroom." << endl;
}
virtual ~Person() {
cout << "Person has left the classroom." << endl;
}
};
class Student : public Person {
public:
void bellRing() override {
cout << "Student is packing up and walking towards the classroom." << endl;
}
~Student() override {
cout << "Student has left the classroom and gone home." << endl;
}
};
class Teacher : public Person {
public:
void bellRing() override {
cout << "Teacher is finishing the class and walking towards the office." << endl;
}
~Teacher() override {
cout << "Teacher has left the office and gone home." << endl;
}
};
class Principal : public Person {
public:
void bellRing() override {
cout << "Principal is checking the school and walking towards the office." << endl;
}
~Principal() override {
cout << "Principal has left the office and gone home." << endl;
}
};
void ring(Person* person) {
person->bellRing();
}
int main() {
Person* person = new Person();
Student* student = new Student();
Teacher* teacher = new Teacher();
Principal* principal = new Principal();
ring(person);
ring(student);
ring(teacher);
ring(principal);
delete person;
delete student;
delete teacher;
delete principal;
return 0;
}
```
输出结果为:
```
Person is walking towards the classroom.
Student is packing up and walking towards the classroom.
Teacher is finishing the class and walking towards the office.
Principal is checking the school and walking towards the office.
Person has left the classroom.
Student has left the classroom and gone home.
Teacher has left the office and gone home.
Principal has left the office and gone home.
```
阅读全文