Design abstract classes and derived classes: Define abstract class Employee, it contains: Data member: string id, string name, int age, double salary Constructor pay(): pure virtual function for calculating the employee’s salary Derived class Manager, it contains: Derived from class Employee. Data members: double fixedSalary Constructor Implement pay() function. Tips: The salary of managers = fixedSalary. Derived class Saleman, it contains: Derived from class Employee. Data member: double salesVolume Implement pay() function. Tips: Saleman salary = 0.04* salesVolume. Declare the base class pointer p and derived class object “Manager A("1001","Zhang San", 25, 5000)” and “Saleman B("1002", "Li Si", 28, 100000)” in the main function, and call the member functions pay() of different objects through the base class pointer.
时间: 2024-02-20 20:02:25 浏览: 77
Here is the implementation of the abstract class Employee and its derived classes Manager and Saleman in C++:
```c++
#include <iostream>
#include <string>
using namespace std;
class Employee {
protected:
string id;
string name;
int age;
double salary;
public:
Employee(string id, string name, int age, double salary) :
id(id), name(name), age(age), salary(salary) {}
virtual void pay() = 0; // pure virtual function
};
class Manager : public Employee {
private:
double fixedSalary;
public:
Manager(string id, string name, int age, double salary, double fixedSalary) :
Employee(id, name, age, salary), fixedSalary(fixedSalary) {}
void pay() {
salary = fixedSalary;
cout << "Manager " << name << "'s salary is " << salary << endl;
}
};
class Saleman : public Employee {
private:
double salesVolume;
public:
Saleman(string id, string name, int age, double salary, double salesVolume) :
Employee(id, name, age, salary), salesVolume(salesVolume) {}
void pay() {
salary = 0.04 * salesVolume;
cout << "Saleman " << name << "'s salary is " << salary << endl;
}
};
int main() {
Employee *p;
Manager A("1001", "Zhang San", 25, 5000, 10000);
Saleman B("1002", "Li Si", 28, 3000, 250000);
p = &A;
p->pay();
p = &B;
p->pay();
return 0;
}
```
In the main function, we declare a base class pointer `p` and two derived class objects `A` and `B`. We then assign the address of object `A` to `p` and call the `pay()` function through the base class pointer, which will call the `pay()` function of the derived class `Manager`. Similarly, we assign the address of object `B` to `p` and call the `pay()` function again, which will call the `pay()` function of the derived class `Saleman`.
Note that we cannot create objects of an abstract class, but we can declare pointers and references to an abstract class. Also, the derived classes must implement the pure virtual function declared in the abstract class, otherwise they will also become abstract classes.
阅读全文