用C++编写一个工资管理程序,将雇员类作为所有类的基类,其派生类包括经理类、销售员类、计件工类和小时工类
时间: 2024-05-07 22:21:27 浏览: 143
以下是一个简单的工资管理程序,包括一个Employee(雇员)基类和四个派生类:Manager(经理)、Salesman(销售员)、PieceWorker(计件工)和HourlyWorker(小时工)。每个类都有自己的工资计算方法和成员变量。
```
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(string name, int id) : name(name), id(id) {}
virtual double salary() const = 0; // 纯虚函数
string getName() const { return name; }
int getId() const { return id; }
private:
string name;
int id;
};
class Manager : public Employee {
public:
Manager(string name, int id, double salary) : Employee(name, id), salary(salary) {}
virtual double salary() const override { return salary; }
private:
double salary;
};
class Salesman : public Employee {
public:
Salesman(string name, int id, double sales, double rate) : Employee(name, id), sales(sales), rate(rate) {}
virtual double salary() const override { return sales * rate; }
private:
double sales;
double rate;
};
class PieceWorker : public Employee {
public:
PieceWorker(string name, int id, int pieces, double rate) : Employee(name, id), pieces(pieces), rate(rate) {}
virtual double salary() const override { return pieces * rate; }
private:
int pieces;
double rate;
};
class HourlyWorker : public Employee {
public:
HourlyWorker(string name, int id, double hours, double rate) : Employee(name, id), hours(hours), rate(rate) {}
virtual double salary() const override { return hours * rate; }
private:
double hours;
double rate;
};
int main() {
Manager m("Tom", 1001, 10000.0);
Salesman s("Jerry", 1002, 40000.0, 0.05);
PieceWorker p("John", 1003, 100, 10.0);
HourlyWorker h("Bob", 1004, 160, 20.0);
cout << "Manager " << m.getName() << " has salary " << m.salary() << endl;
cout << "Salesman " << s.getName() << " has salary " << s.salary() << endl;
cout << "PieceWorker " << p.getName() << " has salary " << p.salary() << endl;
cout << "HourlyWorker " << h.getName() << " has salary " << h.salary() << endl;
return 0;
}
```
这个程序中,Employee 类是一个抽象类,因为它包含了一个纯虚函数 salary(),没有函数体。每个派生类都必须实现它自己的 salary() 函数,否则也会成为抽象类。
四个派生类的构造函数分别需要传入不同的参数,以初始化成员变量。每个类的 salary() 函数根据不同的计算方式,返回对应的工资数额。最后在主函数中创建了四个对象,并输出它们的名字和工资。
阅读全文