5. 定义一个People类作为基类,然后分别定义学生类Student和Teacher类,这两个类公有继承自People类,编写show函数实现多态性(对于学生输出学号,对于教师输出教师号)
时间: 2023-06-11 21:10:02 浏览: 114
下面是代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义People类作为基类
class People {
public:
People() {}
virtual ~People() {} // 基类析构函数要定义为虚函数
virtual void show() { // 定义虚函数,实现多态
cout << "I am a people." << endl;
}
};
// 定义学生类Student
class Student : public People {
public:
Student(int id) : m_id(id) {}
virtual ~Student() {}
virtual void show() { // 重定义虚函数,实现多态
cout << "I am a student. My student ID is " << m_id << "." << endl;
}
private:
int m_id;
};
// 定义教师类Teacher
class Teacher : public People {
public:
Teacher(int id) : m_id(id) {}
virtual ~Teacher() {}
virtual void show() { // 重定义虚函数,实现多态
cout << "I am a teacher. My teacher ID is " << m_id << "." << endl;
}
private:
int m_id;
};
int main() {
People* p1 = new Student(1001); // 基类指针指向派生类对象
People* p2 = new Teacher(2001);
p1->show(); // 多态性:输出学号
p2->show(); // 多态性:输出教师号
delete p1;
delete p2;
return 0;
}
```
输出结果为:
```
I am a student. My student ID is 1001.
I am a teacher. My teacher ID is 2001.
```
以上代码中,定义了People类作为基类,Student类和Teacher类都公有继承自People类。在基类中定义了虚函数show,而在派生类中重定义了show函数,实现了多态性。在main函数中,通过基类指针指向派生类对象,然后调用show函数,输出学号或者教师号。最后删除动态分配的对象。
阅读全文