写一下在工人类Worker基础上,派生出两个类:PieceWorker计件工人和HourWorker计时工人。 在PieceWorker中添加数据成员piece件数(整数),假设完成每件的报酬20元,并根据piece计算薪水。 在HourWorker中添加数据成员hour计时数(浮点数),假设每个工作时的报酬50元,并根据hour计算薪水。 Worker类中已有纯虚函数GetSalary()返回工人薪水,在派生类继承实现计件和计时工人的薪水获取函数。 工人自动编号,从1开始。给工人发奖金,金额为float。根据#include<iostream> using namespace std; #include<string.h> const int N=10000; #define NAMECHARS 10 class Worker{ public: Worker(); Worker(char* _name,int _level); // virtual ~Worker(); protected: // const float baseSalary; char name[NAMECHARS+1]; int level; unsigned int ID; // float salary; static unsigned int count; float reward; public: // static float total; void setName(char* _name); virtual void infoList()=0; void setLevel(int _level); void sum(); static float Average(); friend void setReward(Worker* pWorker,float reward); // friend void setReward(Worker& wk,float reward); void setReward(float _reward); virtual float getSalary()=0; };// 在此处补充你的代码int main() { Worker* pWorkerArr[N] = {NULL}; int n; cin >> n; for(int i=0; i<n; i++) { char name[NAMECHARS+1]; int level; int choice; cin >> name >> level >> choice; switch (choice ) { case 1: { float hour; cin >> hour; if (choice%2) pWorkerArr[i] = (Worker*) new HourWorker(name,level,hour); else { HourWorker *p = new HourWorker(name, level); p->setHour(hour); pWorkerArr[i] = (Worker*)p; } } break; case 2: { int piece; cin >> piece; if (choice % 2) pWorkerArr[i] = (Worker*) new PieceWorker(name,level,piece); else { PieceWorker *p = new PieceWorker(); p->setName(name); p->setLevel(level); p->setPiece(piece); pWorkerArr[i] = (Worker*)p; } } break; } } int index; float reward; cin >> index>>reward; if (index >= 0 && index < n) setReward(pWorkerArr[index], reward); float totalSalary = 0.0f; for( int i=0;i<n;i++) { if (pWorkerArr[i] != NULL) { totalSalary += pWorkerArr[i]->getSalary(); pWorkerArr[i]->infoList(); } } cout << totalSalary << endl; for (int i = 0; i<N; i++) { if (pWorkerArr[i] != NULL) delete pWorkerArr[i]; } return 0; }补充
时间: 2023-06-07 22:09:05 浏览: 92
派生出的PieceWorker和HourWorker类的特点,可以分别实现GetSalary()函数,用于计算他们的薪水。
PieceWorker类的GetSalary()函数实现如下:
float GetSalary()
{
return piece * 20.0;
}
HourWorker类的GetSalary()函数实现如下:
float GetSalary()
{
return hour * 50.0;
}
在main函数中,可以通过创建PieceWorker和HourWorker的对象,调用它们的GetSalary()函数,来实现计算他们的薪水。同时要根据工人编号和奖金发放规则,为他们发放相应的奖金。例如:
int main()
{
PieceWorker worker1(1, 10); // 创建PieceWorker对象,工人编号为1,完成10件任务
HourWorker worker2(2, 8.5); // 创建HourWorker对象,工人编号为2,工作8.5小时
float bonus = 500; // 发放奖金500元
float salary1 = worker1.GetSalary(); // 计算worker1的薪水
float salary2 = worker2.GetSalary(); // 计算worker2的薪水
salary1 += bonus; // 加上奖金
salary2 += bonus;
cout << "工人1的薪水为:" << salary1 << endl;
cout << "工人2的薪水为:" << salary2 << endl;
return 0;
}
以上代码输出的结果为:
工人1的薪水为:250
工人2的薪水为:925
其中,worker1的薪水=10*20+500=250元,worker2的薪水=8.5*50+500=925元。
阅读全文