C++多重继承实战:教师学生身份合一
#include <iostream>
#include <string>
using namespace std;
// 基类:Person(人员类)
class Person {
public:
// 构造函数
Person(string n, string s, string id, string b)
: name(n), sex(s), idCard(id), birthday(b) {}
// 输出人员基本信息
void display() {
cout << "姓名:" << name << endl;
cout << "性别:" << sex << endl;
cout << "身份证号:" << idCard << endl;
cout << "出生年月:" << birthday << endl;
}
protected:
string name; // 姓名
string sex; // 性别
string idCard; // 身份证号
string birthday; // 出生年月
};
// 派生类:Student(学生类,虚继承Person)
class Student : virtual public Person {
public:
// 构造函数:初始化基类和自身成员
Student(string n, string s, string id, string b, string no, double sc)
: Person(n, s, id, b), stuNo(no), score(sc) {}
// 输出学生信息
void displayStudent() {
display(); // 调用基类的display()
cout << "学号:" << stuNo << endl;
cout << "成绩:" << score << endl;
}
protected:
string stuNo; // 学号
double score; // 成绩
};
// 派生类:Teacher(教师类,虚继承Person)
class Teacher : virtual public Person {
public:
// 构造函数:初始化基类和自身成员
Teacher(string n, string s, string id, string b, string t)
: Person(n, s, id, b), title(t) {}
// 输出教师信息
void displayTeacher() {
display(); // 调用基类的display()
cout << "职称:" << title << endl;
}
protected:
string title; // 职称
};
// 多重派生类:Stu_Tech(在职读书的教师类,继承Student和Teacher)
class Stu_Tech : public Student, public Teacher {
public:
// 构造函数:需要直接初始化虚基类Person,避免多重继承的二义性
Stu_Tech(string n, string s, string id, string b, string no, double sc, string t)
: Person(n, s, id, b), Student(n, s, id, b, no, sc), Teacher(n, s, id, b, t) {}
// 输出在职教师信息
void displayAll() {
display(); // 调用Person的display()(无歧义)
cout << "学号:" << stuNo << endl;
cout << "成绩:" << score << endl;
cout << "职称:" << title << endl;
}
};
int main() {
// 测试在职读书的教师类
Stu_Tech st("李华", "男", "110101198505051234", "1985-05", "2026001", 89.5, "副教授");
cout << "===== 在职读书教师信息 =====" << endl;
st.displayAll();
return 0;
}
更多推荐
所有评论(0)