用c定义一个职工类Employee 数据成员 (private): 职工姓名 (char *name)、性别 (bool sex)、年龄、工龄、工资 成员函数 (public): 构造函数:职工基本信息的初始化(姓名、性别、年龄、工龄、工资) 析构函数:释放系统资源(堆空间) 修改职工姓名 修改工资 年薪计算(12×工资+年终奖) 工龄增加 显示职工信息 要求:将类的定义与类成员函数的实现分
时间: 2023-12-19 17:25:39 浏览: 77
thrift 一个有意思的特性:Class名称无关性
以下是用C语言定义一个职工类Employee,数据成员为私有,成员函数为公有:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct {
char *name;
bool sex;
int age;
int workYears;
double salary;
} Employee;
Employee *createEmployee(const char *name, bool sex, int age, int workYears, double salary) {
Employee *employee = (Employee*)malloc(sizeof(Employee));
int length = strlen(name) + 1;
employee->name = (char*)malloc(length);
strcpy(employee->name, name);
employee->sex = sex;
employee->age = age;
employee->workYears = workYears;
employee->salary = salary;
return employee;
}
void destroyEmployee(Employee *employee) {
free(employee->name);
free(employee);
}
void modifyName(Employee *employee, const char *name) {
int length = strlen(name) + 1;
char *newName = (char*)malloc(length);
strcpy(newName, name);
free(employee->name);
employee->name = newName;
}
void modifySalary(Employee *employee, double salary) {
employee->salary = salary;
}
double getAnnualSalary(const Employee *employee) {
return 12 * employee->salary + 5000;
}
void increaseWorkYears(Employee *employee, int years) {
employee->workYears += years;
}
void displayInformation(const Employee *employee) {
printf("Name: %s\n", employee->name);
printf("Sex: %s\n", employee->sex ? "Male" : "Female");
printf("Age: %d\n", employee->age);
printf("Work years: %d\n", employee->workYears);
printf("Salary: %.2f\n", employee->salary);
}
```
使用时,可以通过createEmployee函数创建一个Employee对象,然后使用相关函数对其进行操作,最后使用destroyEmployee函数销毁对象。例如:
```c
int main() {
Employee *employee = createEmployee("Tom", true, 30, 5, 5000);
displayInformation(employee);
modifyName(employee, "Jerry");
modifySalary(employee, 6000);
increaseWorkYears(employee, 1);
printf("Annual salary: %.2f\n", getAnnualSalary(employee));
displayInformation(employee);
destroyEmployee(employee);
return 0;
}
```
阅读全文