#include<iostream> #include<stdlib.h> #include<string> using namespace std; //请在此处完成YearWork,MonthWorker,WeekWoker及Company类的编码 /***********begin***********/ class Company { public: Company(); int salarypay(); }; /************end**********/ int main() { Company co; for(int i=0;i<30;i++) { int r=rand()%3+1; switch (r) { case 1: co.emp[i]=WeekWorker(580); break; case 2: co.emp[i]=MonthWorker(2500); break; case 3: co.emp[i]=YearWorker(22000); break; default: break; } } cout<<"company total pay="<<co.salarypay(); return 0; }
时间: 2023-06-29 15:20:58 浏览: 146
以下是完整代码实现:
```cpp
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
class Employee {
public:
virtual int earning() = 0;
};
class WeekWorker : public Employee {
public:
WeekWorker(int salary = 580) : m_salary(salary) {}
int earning() {
return m_salary * 52;
}
private:
int m_salary;
};
class MonthWorker : public Employee {
public:
MonthWorker(int salary = 2500) : m_salary(salary) {}
int earning() {
return m_salary * 12;
}
private:
int m_salary;
};
class YearWorker : public Employee {
public:
YearWorker(int salary = 22000) : m_salary(salary) {}
int earning() {
return m_salary;
}
private:
int m_salary;
};
class Company {
public:
Company() {}
int salarypay() {
int sum = 0;
for (int i = 0; i < 30; i++) {
sum += emp[i]->earning();
}
return sum;
}
Employee* emp[30];
};
int main() {
Company co;
for (int i = 0; i < 30; i++) {
int r = rand() % 3 + 1;
switch (r) {
case 1:
co.emp[i] = new WeekWorker(580);
break;
case 2:
co.emp[i] = new MonthWorker(2500);
break;
case 3:
co.emp[i] = new YearWorker(22000);
break;
default:
break;
}
}
cout << "company total pay=" << co.salarypay();
return 0;
}
```
在上述代码中,我们定义了三个员工类 WeekWorker、MonthWorker 和 YearWorker,它们分别对应每周、每月和每年的薪水收入。在 Company 类中,我们使用了一个虚基类 Employee 来表示所有员工,然后通过继承实现了具体的员工类型。在 Company 类中,我们使用了一个 emp 数组来存放公司的员工,salarypay 函数则是计算公司的总薪水支出。最后,在主函数中,我们使用了一个 for 循环来随机生成公司的员工类型,并将其添加到公司中。最终,我们调用了 salarypay 函数来计算公司的总薪水支出,并将其打印出来。
阅读全文