先建立一个职工类Employee,包含数据成员name(姓名),ID(编号),以他为基类,派生出经理类Manager和技术人员类Technician,在经理类中增加数据成员salary(月工资),在技术人员类中增加数据成员wage(代表每小时的工资)和hours(工作时长)。在定义类时,所有类中必须包含构造函数、析构函数、修改和获取所有数据成员的函数,以及虚函数计算职工的工资、输出职工的信息,使用c++编写
时间: 2024-03-02 07:50:04 浏览: 60
以下是根据您的要求编写的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Employee {
protected:
string name;
int ID;
public:
Employee(string n, int id) {
name = n;
ID = id;
}
virtual ~Employee() {}
virtual double getSalary() = 0;
virtual void printInfo() {
cout << "name: " << name << ", ID: " << ID << endl;
}
void setName(string n) {
name = n;
}
void setID(int id) {
ID = id;
}
string getName() {
return name;
}
int getID() {
return ID;
}
};
class Manager : public Employee {
private:
double salary;
public:
Manager(string n, int id, double s) : Employee(n, id) {
salary = s;
}
~Manager() {}
double getSalary() {
return salary;
}
void setSalary(double s) {
salary = s;
}
void printInfo() {
cout << "name: " << name << ", ID: " << ID << ", salary: " << salary << endl;
}
};
class Technician : public Employee {
private:
double wage;
double hours;
public:
Technician(string n, int id, double w, double h) : Employee(n, id) {
wage = w;
hours = h;
}
~Technician() {}
double getSalary() {
return wage * hours;
}
void setWage(double w) {
wage = w;
}
void setHours(double h) {
hours = h;
}
void printInfo() {
cout << "name: " << name << ", ID: " << ID << ", wage: " << wage << ", hours: " << hours << endl;
}
};
int main() {
Employee* e1 = new Manager("Tom", 1001, 10000);
Employee* e2 = new Technician("Jerry", 1002, 50, 200);
e1->printInfo();
cout << "salary: " << e1->getSalary() << endl;
e2->printInfo();
cout << "salary: " << e2->getSalary() << endl;
delete e1;
delete e2;
return 0;
}
```
在这个代码中,我们定义了一个基类`Employee`,包含了`name`和`ID`两个数据成员,以及一个纯虚函数`getSalary()`和一个虚函数`printInfo()`。然后我们又从`Employee`类派生出了两个子类`Manager`和`Technician`,分别增加了`salary`、`wage`和`hours`三个数据成员,并重新实现了`getSalary()`和`printInfo()`函数。
在`main()`函数中,我们创建了一个`Manager`对象和一个`Technician`对象,并通过指向基类的指针`Employee*`调用了它们的`printInfo()`和`getSalary()`函数,展示了多态的效果。
注意,在`Employee`类中,我们将析构函数定义为虚函数,这是为了确保在我们使用指向基类的指针删除对象时,能够正确地调用子类的析构函数来释放资源。
阅读全文