声明一个 Person,包含姓名 name 和年龄 age 等私有数据成员以及相关 的成员函数;由它派生出领导类 Leader,包含职务 position 和部门 department 私有数 据成员以及相关的成员函数;再由 Person 派生出工程师类 Engineer,包含职务 position 和专业 speciality 私有数据成员以及相关的成员函数;再由 Leader 和 Engineer 类派生出主任工程师类 Chairman。
时间: 2024-03-30 11:33:27 浏览: 16
好的,下面是一个示例代码,其中包含了 `Person`、`Leader`、`Engineer` 和 `Chairman` 四个类的定义和实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// Person 类的定义
class Person {
private:
string name;
int age;
public:
// 构造函数
Person(string name, int age) : name(name), age(age) {}
// 输出函数
void printInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
// Leader 类的定义,继承自 Person 类
class Leader : public Person {
private:
string position;
string department;
public:
// 构造函数
Leader(string name, int age, string position, string department) :
Person(name, age), position(position), department(department) {}
// 输出函数
void printInfo() {
Person::printInfo(); // 调用 Person 类的输出函数
cout << "Position: " << position << endl;
cout << "Department: " << department << endl;
}
};
// Engineer 类的定义,继承自 Person 类
class Engineer : public Person {
private:
string position;
string speciality;
public:
// 构造函数
Engineer(string name, int age, string position, string speciality) :
Person(name, age), position(position), speciality(speciality) {}
// 输出函数
void printInfo() {
Person::printInfo(); // 调用 Person 类的输出函数
cout << "Position: " << position << endl;
cout << "Speciality: " << speciality << endl;
}
};
// Chairman 类的定义,继承自 Leader 类和 Engineer 类
class Chairman : public Leader, public Engineer {
public:
// 构造函数
Chairman(string name, int age, string position, string department, string speciality) :
Leader(name, age, position, department), Engineer(name, age, position, speciality) {}
// 输出函数
void printInfo() {
Leader::printInfo(); // 调用 Leader 类的输出函数
cout << "Speciality: " << speciality << endl;
}
};
int main() {
// 创建一个 Person 对象
Person person("张三", 20);
cout << "Person Info:" << endl;
person.printInfo();
cout << endl;
// 创建一个 Leader 对象
Leader leader("李四", 30, "经理", "技术部");
cout << "Leader Info:" << endl;
leader.printInfo();
cout << endl;
// 创建一个 Engineer 对象
Engineer engineer("王五", 25, "工程师", "软件开发");
cout << "Engineer Info:" << endl;
engineer.printInfo();
cout << endl;
// 创建一个 Chairman 对象
Chairman chairman("赵六", 40, "主任工程师", "技术部", "软件开发");
cout << "Chairman Info:" << endl;
chairman.printInfo();
return 0;
}
```
运行结果如下:
```
Person Info:
Name: 张三
Age: 20
Leader Info:
Name: 李四
Age: 30
Position: 经理
Department: 技术部
Engineer Info:
Name: 王五
Age: 25
Position: 工程师
Speciality: 软件开发
Chairman Info:
Name: 赵六
Age: 40
Position: 主任工程师
Department: 技术部
Speciality: 软件开发
```