定义一个基类“Role”,类内有数据成员姓名,年龄,性别,有对各数据成员进行读写的函数getXXX()和setXXX(),有一个虚函数display(),该函数显示姓名,年龄,性别等数据成员的值,同时类内至少定义两个构造函数。 从Role类派生出一个“Employee”类,该类具有Role类的所有成员(构造函数除外),并扩展数据成员ID (职工编号)和salary(薪资)。同样要有至少两个构造方法,并重新定义display()函数。 主函数内定义基类指针和派生类对象,并使基类指针指向派生类对象,通过该基类指针访问虚函数display()。
时间: 2024-03-20 20:43:14 浏览: 14
好的,下面是代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Role {
protected:
string name;
int age;
char gender;
public:
Role() {}
Role(string n, int a, char g) {
name = n;
age = a;
gender = g;
}
void setName(string n) { name = n; }
void setAge(int a) { age = a; }
void setGender(char g) { gender = g; }
string getName() { return name; }
int getAge() { return age; }
char getGender() { 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(string n, int a, char g, int id, double s) : Role(n, a, g) {
ID = id;
salary = s;
}
void setID(int id) { ID = id; }
void setSalary(double s) { salary = s; }
int getID() { return ID; }
double getSalary() { return salary; }
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
cout << "ID: " << ID << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Role* ptr = new Employee("John", 25, 'M', 12345, 5000);
ptr->display();
delete ptr;
return 0;
}
```
输出结果为:
```
Name: John
Age: 25
Gender: M
ID: 12345
Salary: 5000
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)