2、编程实现基类Employee,派生类salesManager和HourlyWorker。Employee有数据成员name和ID,表示员工的姓名和编号;salesManager有数据成员salary和sales,代表销售经理的固定月薪和销售额,另外,销售经理固定月薪为5000元并提取销售额的0.5%作为工资;HourlyWorker有数据成员wage和hours,分别代表钟点工的每小时工资数和月工作小时数。要求:定义的所有类中必须包含构造函数,计算职员的月工资的函数定义为纯虚函数来,输出职员的信息函数定义为虚函数。用Emplayee对象指针调用成员函数输出销售经理和钟点工的信息和工资。
时间: 2024-03-08 14:49:22 浏览: 115
好的,这是一个比较典型的面向对象编程题目,我们可以使用C++语言来实现。
首先,需要定义基类Employee,包含数据成员name和ID,以及纯虚函数getSalary()和虚函数printInfo(),代码如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Employee {
protected:
string name;
int ID;
public:
Employee(string name, int ID) : name(name), ID(ID) {}
virtual ~Employee() {}
virtual double getSalary() = 0; // 纯虚函数
virtual void printInfo() {
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
}
};
```
然后,需要定义派生类salesManager和HourlyWorker,分别继承Employee基类,并实现getSalary()函数来计算月工资。代码如下:
```cpp
class salesManager : public Employee {
private:
double salary;
double sales;
public:
salesManager(string name, int ID, double sales)
: Employee(name, ID), sales(sales) {
salary = 5000 + sales * 0.005;
}
double getSalary() { return salary; }
void printInfo() {
Employee::printInfo();
cout << "Salary: " << salary << endl;
cout << "Sales: " << sales << endl;
}
};
class HourlyWorker : public Employee {
private:
double wage;
double hours;
public:
HourlyWorker(string name, int ID, double wage, double hours)
: Employee(name, ID), wage(wage), hours(hours) {}
double getSalary() { return wage * hours; }
void printInfo() {
Employee::printInfo();
cout << "Wage: " << wage << endl;
cout << "Hours: " << hours << endl;
}
};
```
最后,可以使用Employee对象指针调用成员函数输出销售经理和钟点工的信息和工资。代码如下:
```cpp
int main() {
Employee* e1 = new salesManager("Alice", 1, 100000);
e1->printInfo();
cout << "Salary: " << e1->getSalary() << endl;
Employee* e2 = new HourlyWorker("Bob", 2, 50, 160);
e2->printInfo();
cout << "Salary: " << e2->getSalary() << endl;
delete e1;
delete e2;
return 0;
}
```
输出结果如下:
```
Name: Alice
ID: 1
Salary: 5500
Sales: 100000
Salary: 5500
Name: Bob
ID: 2
Wage: 50
Hours: 160
Salary: 8000
```
这样就完成了编程实现基类Employee,派生类salesManager和HourlyWorker的任务。
阅读全文