C++定义了一个基类Person类及其两个派生类(Teacher和Student),再从Teacher类和Student 类派生出Master类,将被重复继承的祖先类Person设置成虚基类。给这些类增加适当的属性和方法,如设置属性值、输出属性值等方法。编写main函数测试之
时间: 2024-05-16 19:12:24 浏览: 176
好的,我明白了你的问题。以下是基类Person类及其两个派生类(Teacher和Student),再从Teacher类和Student类派生出Master类的代码实现,并在每个类中添加适当的属性和方法。
```c++
#include <iostream>
#include <string>
using namespace std;
//基类Person类
class Person {
public:
Person() {}
Person(string n, int a, string s) : name(n), age(a), sex(s) {}
virtual void showInfo() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "性别:" << sex << endl;
}
protected:
string name;
int age;
string sex;
};
//派生类Teacher类
class Teacher : virtual public Person {
public:
Teacher() {}
Teacher(string n, int a, string s, string t) : Person(n, a, s), title(t) {}
void setTitle(string t) {
title = t;
}
string getTitle() {
return title;
}
void showInfo() {
cout << "教师信息:" << endl;
Person::showInfo();
cout << "职称:" << title << endl;
}
private:
string title;
};
//派生类Student类
class Student : virtual public Person {
public:
Student() {}
Student(string n, int a, string s, string id) : Person(n, a, s), stuID(id) {}
void setStuID(string id) {
stuID = id;
}
string getStuID() {
return stuID;
}
void showInfo() {
cout << "学生信息:" << endl;
Person::showInfo();
cout << "学号:" << stuID << endl;
}
private:
string stuID;
};
//从Teacher类和Student类派生出Master类
class Master : public Teacher, public Student {
public:
Master() {}
Master(string n, int a, string s, string t, string id, string r) : Person(n, a, s), Teacher(n, a, s, t), Student(n, a, s, id), research(r) {}
void setResearch(string r) {
research = r;
}
string getResearch() {
return research;
}
void showInfo() {
cout << "研究生信息:" << endl;
Person::showInfo();
cout << "职称:" << Teacher::getTitle() << endl;
cout << "学号:" << Student::getStuID() << endl;
cout << "研究方向:" << research << endl;
}
private:
string research;
};
int main() {
Person p("张三", 20, "男");
p.showInfo();
cout << endl;
Teacher t("李四", 30, "女", "教授");
t.showInfo();
cout << endl;
Student s("王五", 18, "男", "201910001");
s.showInfo();
cout << endl;
Master m("赵六", 25, "女", "讲师", "201920001", "人工智能");
m.showInfo();
cout << endl;
return 0;
}
```
在main函数中,我们分别创建了Person、Teacher、Student和Master四个对象,并调用了它们的showInfo方法输出信息。由于Teacher和Student类都继承了Person类,并且被设置为虚基类,所以在Master类中只需要单独继承Teacher和Student类即可。最后输出的结果如下所示:
```
姓名:张三
年龄:20
性别:男
教师信息:
姓名:李四
年龄:30
性别:女
职称:教授
学生信息:
姓名:王五
年龄:18
性别:男
学号:201910001
研究生信息:
姓名:赵六
年龄:25
性别:女
职称:讲师
学号:201920001
研究方向:人工智能
```
阅读全文