现有一个学校管理系统,在其中包含的处理信息有三个方面,即教师、学生和职工。利用一个菜单来实现对它们的操作。要求使用虚函数。
时间: 2024-03-26 18:35:12 浏览: 4
好的,这是一个很好的问题。我可以给你一个示例代码来演示如何使用虚函数来实现这个学校管理系统。
```cpp
#include <iostream>
using namespace std;
class Person {
public:
virtual void show() = 0;
};
class Teacher : public Person {
public:
void show() {
cout << "This is a teacher." << endl;
}
};
class Student : public Person {
public:
void show() {
cout << "This is a student." << endl;
}
};
class Staff : public Person {
public:
void show() {
cout << "This is a staff." << endl;
}
};
int main() {
int option;
Person *p;
cout << "Please choose an option:" << endl;
cout << "1. Teacher" << endl;
cout << "2. Student" << endl;
cout << "3. Staff" << endl;
cin >> option;
switch (option) {
case 1:
p = new Teacher();
break;
case 2:
p = new Student();
break;
case 3:
p = new Staff();
break;
default:
cout << "Invalid option." << endl;
return 0;
}
p->show();
delete p;
return 0;
}
```
这个程序中,我们定义了一个抽象基类 `Person`,其中包含了一个纯虚函数 `show()`。然后我们派生出三个子类 `Teacher`、`Student` 和 `Staff`,并分别实现了 `show()` 函数。
在主函数中,我们通过用户的选择来创建不同的对象,然后使用指向基类的指针来调用 `show()` 函数。由于 `show()` 函数是虚函数,因此可以正确地调用每个子类的实现。
希望这个示例代码可以帮助你理解如何使用虚函数来实现多态。如果你还有其他问题,请随时问我。