设计person类,包括私有数据成员:姓名、性别和年龄;设计类teacher继承person类,新增私有数据成员:工资;设计student类继承person类,新增私有数据成员:成绩。要求每个类中的数据通过构造函数进行初始化。在主函数中分别定义一个teacher类和student类的对象,并输出这两个对象的值
时间: 2023-11-27 13:55:10 浏览: 89
以下是设计的代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
char sex;
int age;
public:
Person(string name, char sex, int age) : name(name), sex(sex), age(age) {}
void print() {
cout << "Name: " << name << endl;
cout << "Sex: " << sex << endl;
cout << "Age: " << age << endl;
}
};
class Teacher : public Person {
private:
float salary;
public:
Teacher(string name, char sex, int age, float salary) : Person(name, sex, age), salary(salary) {}
void print() {
Person::print();
cout << "Salary: " << salary << endl;
}
};
class Student : public Person {
private:
float score;
public:
Student(string name, char sex, int age, float score) : Person(name, sex, age), score(score) {}
void print() {
Person::print();
cout << "Score: " << score << endl;
}
};
int main() {
Teacher t("Tom", 'M', 35, 5000);
t.print();
Student s("Alice", 'F', 18, 90);
s.print();
return 0;
}
```
输出结果为:
```
Name: Tom
Sex: M
Age: 35
Salary: 5000
Name: Alice
Sex: F
Age: 18
Score: 90
```
阅读全文