编写一个普通的发放工资的函数,函数要求采用多态语句实现工资的发放。编写一个主程序,创建四个类对象,及四个不同类型员工,调用发放工资的普通函数,计算并显示四个人的工资。采用多文件结构实现程序
时间: 2024-03-26 10:42:07 浏览: 15
好的,这是一个典型的面向对象程序设计问题,我可以帮您实现。以下是程序代码:
【Employee.h】
```c++
#include <string>
class Employee {
public:
Employee() {}
Employee(const std::string& name, int salary) : m_name(name), m_salary(salary) {}
virtual void pay() const {
std::cout << m_name << " got paid " << m_salary << " dollars.\n";
}
protected:
std::string m_name;
int m_salary;
};
```
【HourlyEmployee.h】
```c++
#include "Employee.h"
class HourlyEmployee : public Employee {
public:
HourlyEmployee(const std::string& name, int hourlyWage, int hoursWorked)
: Employee(name, hourlyWage * hoursWorked) {}
};
```
【SalariedEmployee.h】
```c++
#include "Employee.h"
class SalariedEmployee : public Employee {
public:
SalariedEmployee(const std::string& name, int salary) : Employee(name, salary) {}
};
```
【CommissionEmployee.h】
```c++
#include "Employee.h"
class CommissionEmployee : public Employee {
public:
CommissionEmployee(const std::string& name, int baseSalary, int commissionRate, int salesVolume)
: Employee(name, baseSalary + commissionRate * salesVolume) {}
};
```
【Contractor.h】
```c++
#include "Employee.h"
class Contractor : public Employee {
public:
Contractor(const std::string& name, int dailyRate, int daysWorked)
: Employee(name, dailyRate * daysWorked) {}
};
```
【main.cpp】
```c++
#include <iostream>
#include "HourlyEmployee.h"
#include "SalariedEmployee.h"
#include "CommissionEmployee.h"
#include "Contractor.h"
void payAll(const Employee* employees[], int count) {
for (int i = 0; i < count; ++i) {
employees[i]->pay();
}
}
int main() {
HourlyEmployee hourly("John", 15, 40);
SalariedEmployee salaried("Mary", 5000);
CommissionEmployee commission("Bob", 1000, 0.1, 50000);
Contractor contractor("Alice", 200, 20);
const Employee* employees[] = { &hourly, &salaried, &commission, &contractor };
payAll(employees, 4);
return 0;
}
```
在这个程序中,我们定义了一个基类 Employee,以及四个派生类 HourlyEmployee、SalariedEmployee、CommissionEmployee 和 Contractor。每个派生类都重载了 pay() 函数,以实现不同的计算工资的方法。然后我们定义了一个 payAll() 函数,它接受一个 Employee* 类型的数组和数组长度,然后遍历数组,调用每个员工的 pay() 函数。最后在 main() 函数中创建了四个不同类型的员工对象,将它们的指针保存在一个数组中,并调用 payAll() 函数。输出结果为:
```
John got paid 600 dollars.
Mary got paid 5000 dollars.
Bob got paid 6000 dollars.
Alice got paid 4000 dollars.
```
其中,John 是 HourlyEmployee,Mary 是 SalariedEmployee,Bob 是 CommissionEmployee,Alice 是 Contractor。
阅读全文