2023.4.25记录

6-3 上课铃响之后 - C/C++ 多态

如本章开篇所述,当小学里的上课铃响之后,学生(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;
}


#include <iostream>
using namespace std;

class Person {
public:
virtual void bellRing() {cout << "I am a person." << endl;}
virtual ~Person() {};
};

class Student: public Person {
public:
virtual void bellRing() override {cout << "I am a student learning in classroom." << endl;}
virtual ~Student() {cout << "A student object destroyed." << endl;}
};

class Teacher: public Person {
public:
virtual void bellRing() override {cout << "I am a teacher teaching in classroom." << endl;}
virtual ~Teacher() {cout << "A teacher object destroyed." << endl;}
};

class Principal: public Person {
public:
virtual void bellRing() override {cout << "I am the principal inspecting in campus." << endl;}
virtual ~Principal() {cout << "A principal object destroyed." << endl;}
};

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;
}

posted @ 2023-04-25 23:13  suN(小硕)  阅读(35)  评论(0编辑  收藏  举报