ü定义一个基类person,保护数据成员:name(姓名),sex(性别),age(年龄),构造函数。 ü派生出教师Teacher类,保护数据成员:title(职称),构造函数。 ü派生出Student类,保护数据成员:score(成绩),构造函数。 ü用多继承的方式定义一个在职研究生(Graduate)派生类私有数据成员wage(工资),构造函数和公有成员函数show()。
时间: 2024-01-11 19:03:32 浏览: 23
以下是代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义 Person 类
class Person {
protected:
string name;
char sex;
int age;
public:
Person(string _name, char _sex, int _age) : name(_name), sex(_sex), age(_age) {}
};
// 定义 Teacher 类
class Teacher : public Person {
protected:
string title;
public:
Teacher(string _name, char _sex, int _age, string _title) : Person(_name, _sex, _age), title(_title) {}
};
// 定义 Student 类
class Student : public Person {
protected:
int score;
public:
Student(string _name, char _sex, int _age, int _score) : Person(_name, _sex, _age), score(_score) {}
};
// 定义 Graduate 类
class Graduate : public Teacher, public Student {
private:
int wage;
public:
Graduate(string _name, char _sex, int _age, string _title, int _score, int _wage)
: Person(_name, _sex, _age), Teacher(_name, _sex, _age, _title), Student(_name, _sex, _age, _score), wage(_wage) {}
void show() {
cout << "姓名:" << name << endl;
cout << "性别:" << sex << endl;
cout << "年龄:" << age << endl;
cout << "职称:" << title << endl;
cout << "成绩:" << score << endl;
cout << "工资:" << wage << endl;
}
};
int main() {
Graduate g("张三", 'M', 30, "教授", 90, 10000);
g.show();
return 0;
}
```
这个代码实现了一个简单的多继承例子,其中 Graduate 类继承了 Teacher 和 Student 类。注意到 Graduate 类中的构造函数要同时传入 Teacher 和 Student 的构造函数参数,而且要按照 Person、Teacher、Student 的顺序来初始化。在 show() 函数中,我们可以输出 Graduate 类的所有数据成员。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)