c++编写一个学生和教师
时间: 2024-05-16 09:13:49 浏览: 141
以下是一个简单的学生和教师类的代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class Student : public Person {
private:
int studentID;
double gpa;
public:
Student(string n, int a, int id, double g) : Person(n, a) {
studentID = id;
gpa = g;
}
void display() {
Person::display();
cout << "Student ID: " << studentID << endl;
cout << "GPA: " << gpa << endl;
}
};
class Teacher : public Person {
private:
string department;
string office;
public:
Teacher(string n, int a, string d, string o) : Person(n, a) {
department = d;
office = o;
}
void display() {
Person::display();
cout << "Department: " << department << endl;
cout << "Office: " << office << endl;
}
};
int main() {
Student stu("Tom", 20, 12345, 3.5);
Teacher tea("Mary", 35, "Computer Science", "Room 123");
stu.display();
cout << endl;
tea.display();
return 0;
}
```
在上面的代码中,我们定义了一个基类 `Person`,然后从它派生出两个子类 `Student` 和 `Teacher`。这两个子类都继承了 `Person` 类的成员变量和成员函数,并且都添加了自己的成员变量和成员函数。在 `main` 函数中,我们创建了一个 `Student` 对象和一个 `Teacher` 对象,并调用它们的 `display` 函数来显示它们的信息。
阅读全文