编写程序(含虚基类的多重继承):设计一个虚基类 Base ,包含姓名和年龄私有数据成员以及相关的成员函数,由它派生出领导类 Leader ,包含职务和部门私有数据成员以及相关的成员函数,再由 Base 派生出类 Engineer ,包含职称和专业私有数据成员以及相关的成员函数。然后由 Leader 和 Engineer 派生出主任工程师类 Chairman 。采用一些数据进行测试。
时间: 2024-04-02 22:34:57 浏览: 21
以下是程序的实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 虚基类 Base
class Base {
protected:
string name; // 姓名
int age; // 年龄
public:
Base(string _name, int _age) : name(_name), age(_age) {}
virtual void showInfo() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
}
};
// 领导类 Leader
class Leader : virtual public Base {
protected:
string job; // 职务
string dept; // 部门
public:
Leader(string _name, int _age, string _job, string _dept)
: Base(_name, _age), job(_job), dept(_dept) {}
virtual void showInfo() {
Base::showInfo();
cout << "职务:" << job << endl;
cout << "部门:" << dept << endl;
}
};
// 工程师类 Engineer
class Engineer : virtual public Base {
protected:
string title; // 职称
string major; // 专业
public:
Engineer(string _name, int _age, string _title, string _major)
: Base(_name, _age), title(_title), major(_major) {}
virtual void showInfo() {
Base::showInfo();
cout << "职称:" << title << endl;
cout << "专业:" << major << endl;
}
};
// 主任工程师类 Chairman
class Chairman : public Leader, public Engineer {
public:
Chairman(string _name, int _age, string _job, string _dept, string _title, string _major)
: Base(_name, _age), Leader(_name, _age, _job, _dept), Engineer(_name, _age, _title, _major) {}
virtual void showInfo() {
Base::showInfo();
cout << "职务:" << job << endl;
cout << "部门:" << dept << endl;
cout << "职称:" << title << endl;
cout << "专业:" << major << endl;
}
};
int main() {
Chairman c("张三", 40, "主任", "研发部", "高级工程师", "计算机科学");
c.showInfo();
return 0;
}
```
程序的输出结果为:
```
姓名:张三
年龄:40
职务:主任
部门:研发部
职称:高级工程师
专业:计算机科学
```