定义一个基类“Role”,类内有数据成员姓名,年龄,性别,有对各数据成员进行读写的函数getXXX()和setXXX(),有一个虚函数display(),该函数显示姓名,年龄,性别等数据成员的值,同时类内至少定义两个构造函数。 从Role类派生出一个“Employee”类,该类具有Role类的所有成员(构造函数除外),并扩展数据成员ID (职工编号)和salary(薪资)。同样要有至少两个构造方法,并重新定义display()函数。 主函数内定义基类指针和派生类对象,并使基类指针指向派生类对象,通过该基类指针访问虚函数display()。
时间: 2024-03-02 08:51:18 浏览: 4
以下是题目要求的基类“Role”和派生类“Employee”的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Role {
protected:
string name;
int age;
char gender;
public:
Role() {}
Role(const string &n, int a, char g) : name(n), age(a), gender(g) {}
virtual ~Role() {}
void setName(const string &n) { name = n; }
void setAge(int a) { age = a; }
void setGender(char g) { gender = g; }
string getName() const { return name; }
int getAge() const { return age; }
char getGender() const { return gender; }
virtual void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
}
};
class Employee : public Role {
private:
int ID;
double salary;
public:
Employee() {}
Employee(const string &n, int a, char g, int id, double s) : Role(n, a, g), ID(id), salary(s) {}
Employee(const string &n, int a, char g) : Role(n, a, g), ID(0), salary(0) {}
virtual ~Employee() {}
void setID(int id) { ID = id; }
void setSalary(double s) { salary = s; }
int getID() const { return ID; }
double getSalary() const { return salary; }
virtual void display() {
Role::display();
cout << "ID: " << ID << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Role *p = new Employee("Tom", 25, 'M', 10001, 5000.0);
p->display();
delete p;
return 0;
}
```
在main函数中,我们定义了一个基类指针p,初始化为指向一个Employee对象。然后通过该基类指针调用虚函数display(),实现了多态性的效果。最后释放了p指向的内存,避免内存泄漏。