假设要管理下述几类人员的如下一些数据。 teacher(教师)类:姓名、性别、年龄、职称、担任 课程; student(学生)类:姓名、性别、年龄、学号、系别; gradstudent(研究生)类:姓名、性别、年龄、学号、系别、导师。 要求每个类只设立构造函数以及显示类对象数据的成员函数(可为虚函数)。编写主函数,说明有关类对象,并对其类成员函数进行简单使用(如果使用了虚函数,在主函数中利用基类指针指向派生类,结合虚函数实现多态)。
时间: 2023-07-10 22:27:56 浏览: 102
好的,我可以帮你编写这个程序。下面是所需的三个类的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
// 基类Person
class Person {
protected:
string name;
char gender;
int age;
public:
Person(string name, char gender, int age) : name(name), gender(gender), age(age) {}
virtual void display() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
};
// 教师类Teacher
class Teacher : public Person {
private:
string title;
string course;
public:
Teacher(string name, char gender, int age, string title, string course) : Person(name, gender, age), title(title), course(course) {}
void display() {
cout << "Teacher:" << endl;
Person::display();
cout << "Title: " << title << endl;
cout << "Course: " << course << endl;
}
};
// 学生类Student
class Student : public Person {
private:
string id;
string department;
public:
Student(string name, char gender, int age, string id, string department) : Person(name, gender, age), id(id), department(department) {}
void display() {
cout << "Student:" << endl;
Person::display();
cout << "ID: " << id << endl;
cout << "Department: " << department << endl;
}
};
// 研究生类GradStudent
class GradStudent : public Student {
private:
string tutor;
public:
GradStudent(string name, char gender, int age, string id, string department, string tutor) : Student(name, gender, age, id, department), tutor(tutor) {}
void display() {
cout << "Graduate Student:" << endl;
Student::display();
cout << "Tutor: " << tutor << endl;
}
};
// 主函数
int main() {
Person* people[3];
people[0] = new Teacher("Tom", 'M', 35, "Associate Professor", "Computer Science");
people[1] = new Student("Lucy", 'F', 20, "20191001", "Computer Science");
people[2] = new GradStudent("Jack", 'M', 25, "20202001", "Computer Science", "Mary");
for (int i = 0; i < 3; i++) {
people[i]->display();
cout << endl;
}
for (int i = 0; i < 3; i++) {
delete people[i];
}
return 0;
}
```
这个程序定义了三个类:`Person`、`Teacher`、`Student`和`GradStudent`,分别表示人员、教师、学生和研究生。每个类都只设立构造函数以及显示类对象数据的成员函数,并使用了虚函数实现多态。在主函数中,定义了一个基类指针数组,分别指向三个派生类的对象,并分别调用了它们的 `display()` 函数,实现了多态效果。
阅读全文