设计person类,包括私有数据成员:姓名、性别和年龄;设计类teacher继承person类,新增私有数据成员:工资;设计student类继承person类,新增私有数据成员:成绩。要求每个类中的数据通过构造函数进行初始化。在主函数中分别定义一个teacher类和student类的对象,并输出这两个对象的值。
时间: 2023-11-22 18:54:32 浏览: 114
以下是实现这个要求的 C++ 代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
char gender;
int age;
public:
Person(string n, char g, int a) : name(n), gender(g), age(a) {}
string getName() const {
return name;
}
char getGender() const {
return gender;
}
int getAge() const {
return age;
}
};
class Teacher : public Person {
private:
double salary;
public:
Teacher(string n, char g, int a, double s) : Person(n, g, a), salary(s) {}
double getSalary() const {
return salary;
}
};
class Student : public Person {
private:
double score;
public:
Student(string n, char g, int a, double sc) : Person(n, g, a), score(sc) {}
double getScore() const {
return score;
}
};
int main() {
Teacher t("Tom", 'M', 35, 50000);
Student s("Lucy", 'F', 18, 90);
cout << "Teacher: " << t.getName() << ", " << t.getGender() << ", " << t.getAge() << ", " << t.getSalary() << endl;
cout << "Student: " << s.getName() << ", " << s.getGender() << ", " << s.getAge() << ", " << s.getScore() << endl;
return 0;
}
```
输出结果:
```
Teacher: Tom, M, 35, 50000
Student: Lucy, F, 18, 90
```
阅读全文