设计person类,包括私有数据成员:姓名、性别和年龄;设计类teacher继承person类,新增私有数据成员:工资;设计student类继承person类,新增私有数据成员:成绩。要求每个类中的数据通过构造函数进行初始化。在主函数中分别定义一个teacher类和student类的对象,并输出这两个对象的值。
时间: 2023-07-15 17:15:45 浏览: 107
以下是对应的C++代码:
```cpp
#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) {}
string getName() { return name; }
string getGender() { return gender; }
int getAge() { return age; }
};
class Teacher : public Person {
private:
double salary;
public:
Teacher(string n, string g, int a, double s) : Person(n, g, a), salary(s) {}
double getSalary() { return salary; }
};
class Student : public Person {
private:
double grade;
public:
Student(string n, string g, int a, double grd) : Person(n, g, a), grade(grd) {}
double getGrade() { return grade; }
};
int main() {
Teacher t("Tom", "Male", 35, 5000.00);
Student s("Alice", "Female", 20, 89.5);
cout << "Teacher's name: " << t.getName() << endl;
cout << "Teacher's gender: " << t.getGender() << endl;
cout << "Teacher's age: " << t.getAge() << endl;
cout << "Teacher's salary: " << t.getSalary() << endl;
cout << endl;
cout << "Student's name: " << s.getName() << endl;
cout << "Student's gender: " << s.getGender() << endl;
cout << "Student's age: " << s.getAge() << endl;
cout << "Student's grade: " << s.getGrade() << endl;
return 0;
}
```
输出结果:
```
Teacher's name: Tom
Teacher's gender: Male
Teacher's age: 35
Teacher's salary: 5000
Student's name: Alice
Student's gender: Female
Student's age: 20
Student's grade: 89.5
```
阅读全文