定义一个人员类Person,包括姓名、性别、年龄等数据成员和用于输入、输出的成员函数,设计构造函数完成数据初始化操作。在此基础上派生出学生类Student类(增加成绩)和教师类Teacher(增加教龄),并实现对学生和教师信息的输入和输出。
时间: 2024-10-27 19:08:33 浏览: 41
首先,我们可以创建一个基础的`Person`类,包含姓名、性别和年龄的基本属性,以及用于设置和获取这些属性的方法:
```cpp
class Person {
public:
// 数据成员
std::string name;
char gender;
int age;
// 构造函数
Person(const std::string& name, char gender, int age)
: name(name), gender(gender), age(age) {}
// 输入和输出方法
void setInput(std::string name, char gender, int age) {
this->name = name;
this->gender = gender;
this->age = age;
}
void display() const {
std::cout << "Name: " << name << ", Gender: " << (gender == 'M' ? "Male" : "Female") << ", Age: " << age << std::endl;
}
};
```
接着,我们派生出`Student`和`Teacher`两个类,分别添加特有的属性:
```cpp
class Student : public Person {
public:
float score; // 学生成绩
Student(const std::string& name, char gender, int age, float score)
: Person(name, gender, age), score(score) {}
void setScore(float score) { this->score = score; }
void display() const override {
Person::display();
std::cout << "Score: " << score << std::endl;
}
};
class Teacher : public Person {
public:
int yearsOfExperience; // 教师教龄
Teacher(const std::string& name, char gender, int age, int yearsOfExperience)
: Person(name, gender, age), yearsOfExperience(yearsOfExperience) {}
void setYearsOfExperience(int years) { this->yearsOfExperience = years; }
void display() const override {
Person::display();
std::cout << "Years of Experience: " << yearsOfExperience << std::endl;
}
};
```
现在你可以创建这些类的对象,并通过它们提供的成员函数来输入和输出信息:
```cpp
int main() {
Student student("张三", 'M', 18, 90.5);
student.setInput("李四", 'F', 19, 95.0); // 这里展示的是如何修改学生的信息
student.display();
Teacher teacher("王五", 'M', 40, 15);
teacher.setYearsOfExperience(20); // 设置教龄
teacher.display();
return 0;
}
```
阅读全文