C++面向对象编程:实现老师、学生和研究生类模拟教学系统
#include <iostream>
#include <string>
using namespace std;
class Teacher {
private:
string name;
int age;
public:
Teacher(string n, int a) {
name = n;
age = a;
}
void teach() {
cout << 'Teacher ' << name << ' is teaching.' << endl;
}
};
class Student {
private:
string name;
string studentID;
public:
Student(string n, string id) {
name = n;
studentID = id;
}
void study() {
cout << 'Student ' << name << ' is studying.' << endl;
}
};
class Graduate : public Teacher, public Student {
private:
string studentID;
public:
Graduate(string n, int a, string id) : Teacher(n, a), Student(n, id) {
studentID = id;
}
void teach() {
cout << 'Graduate ' << name << ' is teaching.' << endl;
}
void study() {
cout << 'Graduate ' << name << ' is studying.' << endl;
}
};
int main() {
Teacher teacher('Tom', 40);
Student student('John', '123456');
Graduate graduate('Alice', 25, '987654');
teacher.teach();
student.study();
graduate.teach();
graduate.study();
return 0;
}
代码解析
这段代码定义了三个类: Teacher (老师)、 Student (学生)和 Graduate (研究生)。
Teacher类和Student类分别描述了老师和学生的信息和职责。Graduate类继承了Teacher和Student类的属性和方法,并重写了teach()和study()方法,体现了研究生既是学生也要承担一部分教学任务的特点。
在 main 函数中,我们创建了一个 Teacher 对象、一个 Student 对象和一个 Graduate 对象,并调用它们的 teach() 和 study() 方法来展示不同身份的职责执行结果。
运行结果
Teacher Tom is teaching.
Student John is studying.
Graduate Alice is teaching.
Graduate Alice is studying.
总结
这段代码清晰地展示了如何使用C++的类和继承概念来模拟现实世界中的关系和行为。通过创建不同的类来代表不同的角色,并使用继承来表示角色之间的关系,我们可以编写出结构清晰、易于理解和维护的代码。
原文地址: https://www.cveoy.top/t/topic/f31E 著作权归作者所有。请勿转载和采集!