编写一个普通的发放工资的函数,函数要求采用多态语句实现工资的发放。编写一个主程序,创建四个类对象,及四个不同类型员工,调用发放工资的普通函数,计算并显示四个人的工资。采用多文件结构实现程序
时间: 2024-03-26 13:41:30 浏览: 48
好的,以下是实现该要求的代码:
首先是 Employee.h 文件,定义了一个基类 Employee:
```
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
class Employee {
public:
Employee(std::string name);
virtual ~Employee();
virtual double calculate_salary() = 0;
protected:
std::string m_name;
};
#endif
```
然后是 SalariedEmployee.h 文件,继承自 Employee 类,实现了 calculate_salary 函数:
```
#ifndef SALARIEDEMPLOYEE_H
#define SALARIEDEMPLOYEE_H
#include "Employee.h"
class SalariedEmployee : public Employee {
public:
SalariedEmployee(std::string name, double base_salary);
virtual ~SalariedEmployee();
virtual double calculate_salary();
private:
double m_base_salary;
};
#endif
```
接着是 HourlyEmployee.h 文件,同样继承自 Employee 类,实现了 calculate_salary 函数:
```
#ifndef HOURLYEMPLOYEE_H
#define HOURLYEMPLOYEE_H
#include "Employee.h"
class HourlyEmployee : public Employee {
public:
HourlyEmployee(std::string name, double hourly_rate, double hours_worked);
virtual ~HourlyEmployee();
virtual double calculate_salary();
private:
double m_hourly_rate;
double m_hours_worked;
};
#endif
```
然后是 CommissionEmployee.h 文件,同样继承自 Employee 类,实现了 calculate_salary 函数:
```
#ifndef COMMISSIONEMPLOYEE_H
#define COMMISSIONEMPLOYEE_H
#include "Employee.h"
class CommissionEmployee : public Employee {
public:
CommissionEmployee(std::string name, double commission_rate, double sales);
virtual ~CommissionEmployee();
virtual double calculate_salary();
private:
double m_commission_rate;
double m_sales;
};
#endif
```
最后是 Payroll.cpp 文件,实现了发放工资的普通函数,以及主程序:
```
#include <iostream>
#include "Employee.h"
#include "SalariedEmployee.h"
#include "HourlyEmployee.h"
#include "CommissionEmployee.h"
double calculate_payroll(Employee* employee) {
return employee->calculate_salary();
}
int main() {
SalariedEmployee salaried_employee("John Smith", 4000);
HourlyEmployee hourly_employee("Jane Doe", 20, 40);
CommissionEmployee commission_employee("Bob Johnson", 0.1, 5000);
Employee* employee = new Employee("Mary Brown");
std::cout << "Salaried employee " << salaried_employee.calculate_salary() << std::endl;
std::cout << "Hourly employee " << hourly_employee.calculate_salary() << std::endl;
std::cout << "Commission employee " << commission_employee.calculate_salary() << std::endl;
std::cout << "Employee " << employee->calculate_salary() << std::endl;
delete employee;
employee = nullptr;
return 0;
}
```
以上代码实现了要求的功能,即创建了四个不同类型的员工对象,并调用发放工资的普通函数,计算并显示四个人的工资。
阅读全文