2、先建立一个职工类Employee,包含数据成员name(姓名),ID(编号),以他为基类,派生出经理类Manager和技术人员类Technician,在经理类中增加数据成员salary(月工资),在技术人员类中增加数据成员wage(代表每小时的工资)和hours(工作时长)。在定义类时,所有类中必须包含构造函数、析构函数、修改和获取所有数据成员的函数,以及虚函数计算职工的工资、输出职工的信息。用C++
时间: 2024-03-02 08:52:03 浏览: 222
以下是代码实现:
```
#include <iostream>
#include <string>
using namespace std;
class Employee {
protected:
string name;
int ID;
public:
Employee(const string& n, int id) : name(n), ID(id) {}
virtual ~Employee() {}
virtual void setSalary(double s) {}
virtual double getSalary() const { return 0; }
virtual void setWage(double w) {}
virtual double getWage() const { return 0; }
virtual void setHours(int h) {}
virtual int getHours() const { return 0; }
virtual double calculateSalary() const { return 0; }
virtual void printInfo() const {
cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
}
};
class Manager : public Employee {
private:
double salary;
public:
Manager(const string& n, int id, double s) : Employee(n, id), salary(s) {}
void setSalary(double s) { salary = s; }
double getSalary() const { return salary; }
double calculateSalary() const { return salary; }
void printInfo() const {
Employee::printInfo();
cout << "Salary: " << salary << endl;
}
};
class Technician : public Employee {
private:
double wage;
int hours;
public:
Technician(const string& n, int id, double w, int h) : Employee(n, id), wage(w), hours(h) {}
void setWage(double w) { wage = w; }
double getWage() const { return wage; }
void setHours(int h) { hours = h; }
int getHours() const { return hours; }
double calculateSalary() const { return wage * hours; }
void printInfo() const {
Employee::printInfo();
cout << "Wage per hour: " << wage << endl;
cout << "Working hours: " << hours << endl;
}
};
int main() {
Manager m("John Smith", 1001, 5000);
m.printInfo();
cout << "Calculated salary: " << m.calculateSalary() << endl;
m.setSalary(6000);
cout << "New salary: " << m.getSalary() << endl;
Technician t("Mary Johnson", 2001, 20, 160);
t.printInfo();
cout << "Calculated salary: " << t.calculateSalary() << endl;
t.setWage(25);
t.setHours(180);
cout << "New wage: " << t.getWage() << endl;
cout << "New hours: " << t.getHours() << endl;
cout << "New calculated salary: " << t.calculateSalary() << endl;
return 0;
}
```
在上述代码中,我们先定义了一个基类Employee,其中包含了所有职工类的共同数据成员和方法。然后,我们分别派生出Manager和Technician类,并在各自的类中增加了不同的数据成员和方法,用于计算和输出工资信息。在定义类时,我们使用了虚函数,这样在使用指向基类的指针时,可以正确调用派生类的方法。最后,在main函数中,我们创建了两个具体的职工对象,并进行了测试。
阅读全文