从实验6中的people(人员)类派生出student(学生)类,添加属性:班号char classNO[7];从people类派生出teacher(教师)类,添加属性:职务char principalship[11]、部门char department[21]。从student类中派生出graduate(研究生)类,添加属性:专业char subject[21]、导师teacher adviser;从graduate类和teacher类派生出TA(助教生)类,注意虚基类的使用。重载相应的成员函数,测试这些类。
时间: 2023-06-13 16:05:12 浏览: 241
设计一个Person类,有Person类派生一个Student类和一个Teacher类
以下是相应的代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class People {
protected:
char name[21];
int age;
char gender;
public:
People(const char* _name, int _age, char _gender) {
strcpy(name, _name);
age = _age;
gender = _gender;
}
virtual void display() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "性别:" << gender << endl;
}
};
class Student : public People {
protected:
char classNO[7];
public:
Student(const char* _name, int _age, char _gender, const char* _classNO)
: People(_name, _age, _gender) {
strcpy(classNO, _classNO);
}
virtual void display() {
People::display();
cout << "班号:" << classNO << endl;
}
};
class Teacher : virtual public People {
protected:
char principalship[11];
char department[21];
public:
Teacher(const char* _name, int _age, char _gender, const char* _principalship, const char* _department)
: People(_name, _age, _gender) {
strcpy(principalship, _principalship);
strcpy(department, _department);
}
virtual void display() {
People::display();
cout << "职务:" << principalship << endl;
cout << "部门:" << department << endl;
}
};
class Graduate : public Student {
protected:
char subject[21];
Teacher* adviser;
public:
Graduate(const char* _name, int _age, char _gender, const char* _classNO, const char* _subject, Teacher* _adviser)
: People(_name, _age, _gender), Student(_name, _age, _gender, _classNO) {
strcpy(subject, _subject);
adviser = _adviser;
}
virtual void display() {
Student::display();
cout << "专业:" << subject << endl;
cout << "导师:" << adviser->name << endl;
}
};
class TA : public Graduate, public Teacher {
public:
TA(const char* _name, int _age, char _gender, const char* _classNO, const char* _subject, Teacher* _adviser, const char* _principalship, const char* _department)
: People(_name, _age, _gender),
Graduate(_name, _age, _gender, _classNO, _subject, _adviser),
Teacher(_name, _age, _gender, _principalship, _department) {}
virtual void display() {
Graduate::display();
cout << "职务:" << principalship << endl;
cout << "部门:" << department << endl;
}
};
int main() {
Teacher t1("张三", 35, 'M', "教授", "计算机科学与技术系");
Graduate g1("李四", 25, 'M', "01", "计算机科学与技术", &t1);
TA ta1("王五", 24, 'F', "02", "计算机科学与技术", &t1, "助教", "计算机科学与技术系");
t1.display();
cout << "----------------------" << endl;
g1.display();
cout << "----------------------" << endl;
ta1.display();
return 0;
}
```
运行结果如下:
```
姓名:张三
年龄:35
性别:M
职务:教授
部门:计算机科学与技术系
----------------------
姓名:李四
年龄:25
性别:M
班号:01
专业:计算机科学与技术
导师:张三
----------------------
姓名:王五
年龄:24
性别:F
班号:02
专业:计算机科学与技术
导师:张三
职务:助教
部门:计算机科学与技术系
```
阅读全文