2、定义一个雇员类Employee,包含char型数组成员变量m_cName(姓名)和m_cNo(编号),int型成员变量m_nDepartment(部门号),成员函数SetName(char *pcName)、SetNo(char *pcNo)和SetDept(int nDept)分别用来设置姓名、编号和部门号,Display()函数用来输出雇员的信息,还包含一个构造函数Employee(char *pcName, char *pcNo, int nDept)。定义一个经理类Manager,派生于雇员类Employee,新增成员变量m_nLevel表示级别和成员函数SetLvl(int nLvl)用来设置m_nLevel,重定义Display()用来输出经理的信息。 要求: (1)Manager类的成员函数可以直接访问Employee类中的成员变量,但类的外部不能直接访问。 (2)在主函数中分别创建一个雇员类对象和一个经理类对象,并输出对象的信息。
时间: 2024-03-22 21:41:59 浏览: 62
以下是Employee类和Manager类的定义及实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Employee {
private:
char m_cName[20];
char m_cNo[10];
int m_nDepartment;
public:
Employee(char *pcName, char *pcNo, int nDept) {
strcpy(m_cName, pcName);
strcpy(m_cNo, pcNo);
m_nDepartment = nDept;
}
void SetName(char *pcName) {
strcpy(m_cName, pcName);
}
void SetNo(char *pcNo) {
strcpy(m_cNo, pcNo);
}
void SetDept(int nDept) {
m_nDepartment = nDept;
}
void Display() {
cout << "Name: " << m_cName << endl;
cout << "No.: " << m_cNo << endl;
cout << "Department: " << m_nDepartment << endl;
}
};
class Manager : public Employee {
private:
int m_nLevel;
public:
Manager(char *pcName, char *pcNo, int nDept, int nLvl) : Employee(pcName, pcNo, nDept) {
m_nLevel = nLvl;
}
void SetLvl(int nLvl) {
m_nLevel = nLvl;
}
void Display() {
Employee::Display();
cout << "Level: " << m_nLevel << endl;
}
};
```
在主函数中,我们可以创建Employee和Manager对象,并分别调用它们的成员函数来设置和输出信息:
```c++
int main() {
Employee emp("Tom", "001", 1);
emp.Display();
Manager mgr("Jack", "002", 2, 3);
mgr.Display();
return 0;
}
```
输出结果为:
```
Name: Tom
No.: 001
Department: 1
Name: Jack
No.: 002
Department: 2
Level: 3
```
阅读全文