定义一个职工类Employee 数据成员 (private): 职工姓名 (char *name)、性别 (bool sex)、年龄、工龄、工资 成员函数 (public): 构造函数:职工基本信息的初始化(姓名、性别、年龄、工龄、工资) 析构函数:释放系统资源(堆空间) 修改职工姓名 修改工资 年薪计算(12×工资+年终奖) 工龄增加 显示职工信息
时间: 2023-12-19 10:25:33 浏览: 40
下面是职工类 Employee 的代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Employee {
private:
char *name; // 职工姓名
bool sex; // 性别,true 为男性,false 为女性
int age; // 年龄
int workYears; // 工龄
double salary; // 工资
public:
// 构造函数:职工基本信息的初始化(姓名、性别、年龄、工龄、工资)
Employee(const char *name, bool sex, int age, int workYears, double salary) {
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
this->sex = sex;
this->age = age;
this->workYears = workYears;
this->salary = salary;
}
// 析构函数:释放系统资源(堆空间)
~Employee() {
delete[] name;
}
// 修改职工姓名
void setName(const char *name) {
delete[] this->name;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
// 修改工资
void setSalary(double salary) {
this->salary = salary;
}
// 年薪计算(12×工资+年终奖)
double getAnnualSalary(double bonus) {
return 12 * salary + bonus;
}
// 工龄增加
void increaseWorkYears() {
workYears++;
}
// 显示职工信息
void display() {
cout << "姓名:" << name << endl;
cout << "性别:" << (sex ? "男" : "女") << endl;
cout << "年龄:" << age << endl;
cout << "工龄:" << workYears << " 年" << endl;
cout << "工资:" << salary << " 元/月" << endl;
}
};
```
可以通过以下方式创建一个职工对象,并且调用成员函数修改和显示职工信息:
```c++
int main() {
Employee employee("张三", true, 25, 2, 5000);
employee.display();
employee.setName("李四");
employee.setSalary(6000);
employee.increaseWorkYears();
employee.display();
cout << "年薪:" << employee.getAnnualSalary(10000) << endl;
return 0;
}
```
阅读全文