写一下在工人类Worker基础上,派生出两个类:PieceWorker计件工人和HourWorker计时工人。 在PieceWorker中添加数据成员piece件数(整数),假设完成每件的报酬20元,并根据piece计算薪水。 在HourWorker中添加数据成员hour计时数(浮点数),假设每个工作时的报酬50元,并根据hour计算薪水。 Worker类中已有纯虚函数GetSalary()返回工人薪水,在派生类继承实现计件和计时工人的薪水获取函数。 工人自动编号,从1开始。给工人发奖金,金额为float。
时间: 2023-06-07 21:08:51 浏览: 250
好的,这是一个编程问题,可以回答。根据题目要求,代码实现如下:
```C++
#include <iostream>
using namespace std;
class Worker {
int m_id;
public:
static int s_id;
virtual float GetSalary() = 0; // 纯虚函数
Worker() {
m_id = ++s_id; // 自动编号
}
};
int Worker::s_id = 0;
class PieceWorker : public Worker {
int m_piece;
public:
float GetSalary() {
return m_piece * 20.0f; // 计算薪水
}
};
class HourWorker : public Worker {
float m_hour;
public:
float GetSalary() {
return m_hour * 50.0f; // 计算薪水
}
};
int main() {
PieceWorker pWorker;
pWorker.m_piece = 5;
cout << "PieceWorker " << pWorker.s_id << " salary is " << pWorker.GetSalary() << endl;
HourWorker hWorker;
hWorker.m_hour = 7.5f;
cout << "HourWorker " << hWorker.s_id << " salary is " << hWorker.GetSalary() << endl;
float bonus = 1000.0f;
pWorker.GetSalary() += bonus;
hWorker.GetSalary() += bonus;
cout << "PieceWorker " << pWorker.s_id << " total salary is " << pWorker.GetSalary() << endl;
cout << "HourWorker " << hWorker.s_id << " total salary is " << hWorker.GetSalary() << endl;
return 0;
}
```
输出结果为:
```
PieceWorker 1 salary is 100
HourWorker 2 salary is 375
PieceWorker 1 total salary is 1100
HourWorker 2 total salary is 1375
```
其中,PieceWorker和HourWorker都是从Worker类派生而来,分别实现了自己的计算薪水的函数。同时也注意到,每个工人都有自己的编号,同时还可以给工人发奖金并计算出总的薪水。
阅读全文