1.人员类与派生类 (1)定义名为CPerson的类,该类拥有属性:char *name、char sex和int age: (2)为CPerson类设计相应的构造函数、析构函数和成员函数,能通过成员函数设置和获取数据成员; (3)由类CPerson派生出子类CEmployee,为该类增加两个新的数据成员,分别用于表示部门(department)和薪水(salary); (4)要求派生类CEmployee的构造函数显式调用基类CPerson的构造函数: (5)为派生类CEmployee增加需要的成员函数; (6)在主程序中定义CEmployee的对象,观察构造函数与析构函数的调用顺序;
时间: 2023-05-14 11:04:39 浏览: 175
CPerson类的定义如下:
```c++
class CPerson {
public:
CPerson(char* name, char sex, int age);
~CPerson();
void setName(char* name);
void setSex(char sex);
void setAge(int age);
char* getName();
char getSex();
int getAge();
private:
char* name;
char sex;
int age;
};
```
CEmployee类的定义如下:
```c++
class CEmployee : public CPerson {
public:
CEmployee(char* name, char sex, int age, char* department, int salary);
~CEmployee();
void setDepartment(char* department);
void setSalary(int salary);
char* getDepartment();
int getSalary();
private:
char* department;
int salary;
};
```
CEmployee类的构造函数需要显式调用基类CPerson的构造函数,代码如下:
```c++
CEmployee::CEmployee(char* name, char sex, int age, char* department, int salary) : CPerson(name, sex, age) {
this->department = department;
this->salary = salary;
}
```
CEmployee类的成员函数如下:
```c++
void CEmployee::setDepartment(char* department) {
this->department = department;
}
void CEmployee::setSalary(int salary) {
this->salary = salary;
}
char* CEmployee::getDepartment() {
return department;
}
int CEmployee::getSalary() {
return salary;
}
```
在主程序中定义CEmployee的对象,观察构造函数与析构函数的调用顺序,代码如下:
```c++
int main() {
CEmployee employee("张三", '男', 25, "技术部", 10000);
return 0;
}
```
输出结果为:
```
CPerson 构造函数
CEmployee 构造函数
CEmployee 析构函数
CPerson 析构函数
```
阅读全文