设计person类,包括私有数据成员:姓名、性别和年龄;设计类teacher继承person类,新增私有数据成员:工资;设计student类继承person类,新增私有数据成员:成绩。要求每个类中的数据通过构造函数进行初始化。在主函数中分别定义一个teacher类和student类的对象,并输出这两个对象的值
时间: 2023-11-28 19:48:23 浏览: 202
设计一个人类person,包括人员编号和姓名等数据成员以及相关的成员函数
以下是对应的代码实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
string gender;
int age;
public:
Person(string n, string g, int a) : name(n), gender(g), age(a) {}
void showInfo() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
};
class Teacher : public Person {
private:
int salary;
public:
Teacher(string n, string g, int a, int s) : Person(n, g, a), salary(s) {}
void showInfo() {
Person::showInfo();
cout << "Salary: " << salary << endl;
}
};
class Student : public Person {
private:
int score;
public:
Student(string n, string g, int a, int s) : Person(n, g, a), score(s) {}
void showInfo() {
Person::showInfo();
cout << "Score: " << score << endl;
}
};
int main() {
Teacher t("Tom", "Male", 35, 5000);
Student s("Lucy", "Female", 18, 90);
cout << "Teacher's Info:" << endl;
t.showInfo();
cout << endl;
cout << "Student's Info:" << endl;
s.showInfo();
return 0;
}
```
输出结果:
```
Teacher's Info:
Name: Tom
Gender: Male
Age: 35
Salary: 5000
Student's Info:
Name: Lucy
Gender: Female
Age: 18
Score: 90
```
阅读全文