#include <iostream> #include <string> using namespace std; class Employee { public: Employee(string n = "", int a = 0) : name(n), age(a) {} void showInfo() { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } private: string name; int age; }; class Leader : virtual public Employee { public: Leader(string t = "", string d = "") : title(t), dept(d) {} void showInfo() { Employee::showInfo(); cout << "Title: " << title << endl; cout << "Department: " << dept << endl; } private: string title; string dept; }; class Engineer : virtual public Employee { public: Engineer(string p = "", string m = "") : profession(p), major(m) {} void showInfo() { Employee::showInfo(); cout << "Profession: " << profession << endl; cout << "Major: " << major << endl; } private: string profession; string major; }; class Chairman : public Leader, public Engineer { public: Chairman(string n, int a, string t, string d, string p, string m) : Employee(n, a), Leader(t, d), Engineer(p, m) {} void showInfo() { Employee::showInfo(); cout << "Title: " << Leader::Title << endl; cout << "Department: " << Leader::dept << endl; cout << "Profession: " << Engineer::profession << endl; cout << "Major: " << Engineer::major << endl; } }; int main() { Chairman c("Alice", 35, "Manager", "R&D", "Senior Engineer", "Computer Science"); c.showInfo(); return 0; }怎么改
时间: 2024-04-02 20:32:02 浏览: 58
这段代码实现了一个多重继承的例子,但存在以下问题:
1. 在 `Chairman` 的 `showInfo` 函数中,访问了 `Leader` 和 `Engineer` 的私有成员,应该改为访问其公有成员。
2. `Leader` 和 `Engineer` 的 `showInfo` 函数并没有实现多重继承的需求,应该去掉。
3. 在 `Chairman` 的构造函数中,应该调用 `Employee` 的构造函数来初始化 `Employee` 的成员变量。
下面是修改后的代码:
```
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(string n = "", int a = 0) : name(n), age(a) {}
void showInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
private:
string name;
int age;
};
class Leader : virtual public Employee {
public:
Leader(string t = "", string d = "") : title(t), dept(d) {}
string getTitle() const {
return title;
}
string getDept() const {
return dept;
}
private:
string title;
string dept;
};
class Engineer : virtual public Employee {
public:
Engineer(string p = "", string m = "") : profession(p), major(m) {}
string getProfession() const {
return profession;
}
string getMajor() const {
return major;
}
private:
string profession;
string major;
};
class Chairman : public Leader, public Engineer {
public:
Chairman(string n, int a, string t, string d, string p, string m) : Employee(n, a), Leader(t, d), Engineer(p, m) {}
void showInfo() {
Employee::showInfo();
cout << "Title: " << Leader::getTitle() << endl;
cout << "Department: " << Leader::getDept() << endl;
cout << "Profession: " << Engineer::getProfession() << endl;
cout << "Major: " << Engineer::getMajor() << endl;
}
};
int main() {
Chairman c("Alice", 35, "Manager", "R&D", "Senior Engineer", "Computer Science");
c.showInfo();
return 0;
}
```
阅读全文