• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
7777lcc
博客园    首页    新随笔    联系   管理    订阅  订阅

虚函数、抽象类(上课铃)

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;

}

};

posted @ 2023-05-10 00:29  卖核弹的小女孩~  阅读(72)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3