2. 编写程序(含虚基类的多重继承):设计一个虚基类Base,包含姓名和年龄私有数据成员以及相关的成员函数,由它派生出领导类Leader,包含职务和部门私有数据成员以及相关的成员函数,再由Base派生出类Engineer,包含职称和专业私有数据成员以及相关的成员函数。然后由Leader和Engineer派生出主任工程师类Chairman。采用一些数据进行测试。
时间: 2024-04-02 21:37:04 浏览: 95
以下是一种实现方式:
```c++
#include <iostream>
#include <string>
using namespace std;
class Base {
protected:
string m_strName;
int m_nAge;
public:
Base(const string& strName, int nAge) : m_strName(strName), m_nAge(nAge) {}
virtual void ShowInfo() {
cout << "Name: " << m_strName << ", Age: " << m_nAge << endl;
}
};
class Leader : virtual public Base {
protected:
string m_strPosition;
string m_strDepartment;
public:
Leader(const string& strName, int nAge, const string& strPosition, const string& strDepartment)
: Base(strName, nAge), m_strPosition(strPosition), m_strDepartment(strDepartment) {}
virtual void ShowInfo() {
Base::ShowInfo();
cout << "Position: " << m_strPosition << ", Department: " << m_strDepartment << endl;
}
};
class Engineer : virtual public Base {
protected:
string m_strTitle;
string m_strMajor;
public:
Engineer(const string& strName, int nAge, const string& strTitle, const string& strMajor)
: Base(strName, nAge), m_strTitle(strTitle), m_strMajor(strMajor) {}
virtual void ShowInfo() {
Base::ShowInfo();
cout << "Title: " << m_strTitle << ", Major: " << m_strMajor << endl;
}
};
class Chairman : public Leader, public Engineer {
public:
Chairman(const string& strName, int nAge, const string& strPosition, const string& strDepartment,
const string& strTitle, const string& strMajor)
: Base(strName, nAge), Leader(strName, nAge, strPosition, strDepartment), Engineer(strName, nAge, strTitle, strMajor) {}
virtual void ShowInfo() {
Base::ShowInfo();
cout << "Position: " << m_strPosition << ", Department: " << m_strDepartment
<< ", Title: " << m_strTitle << ", Major: " << m_strMajor << endl;
}
};
int main() {
Chairman chairman("Tom", 45, "Chairman", "Engineering", "Chief Engineer", "Mechanical Engineering");
chairman.ShowInfo();
return 0;
}
```
在这个程序中,定义了一个虚基类 Base,包含姓名和年龄私有数据成员以及 ShowInfo() 成员函数,由它派生出 Leader 类和 Engineer 类。Leader 类包含职务和部门私有数据成员以及 ShowInfo() 成员函数,Engineer 类包含职称和专业私有数据成员以及 ShowInfo() 成员函数。然后由 Leader 和 Engineer 派生出主任工程师类 Chairman。在主函数中创建一个 Chairman 类对象,并调用其 ShowInfo() 成员函数来输出相关信息。
需要注意的是,Leader 和 Engineer 类都使用了虚继承来避免由于多重继承而引起的二义性问题。在 Chairman 类的构造函数中,需要显式调用 Base、Leader 和 Engineer 类的构造函数来初始化基类对象。同时,由于 Leader 和 Engineer 类都从 Base 类继承而来,所以在它们的构造函数中也需要调用 Base 类的构造函数。
阅读全文