用c++编写一个学生和教师数据输入和显示程序,学生数据有学号、姓名、班号和成绩;教师数据有编号、姓名、职称和部门。要求将编号、姓名输入和显示设计成一个类person,并作为学生类student和teacher类的基类
时间: 2024-04-03 19:31:09 浏览: 119
编写一个学生和教师数据输入和显示程序
好的,以下是用C++编写的程序示例:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 定义Person类
class Person {
public:
Person(string id, string name) : id_(id), name_(name) {}
string get_id() const { return id_; }
string get_name() const { return name_; }
private:
string id_;
string name_;
};
// 定义Student类,继承自Person类
class Student : public Person {
public:
Student(string id, string name, string class_id, int score) : Person(id, name), class_id_(class_id), score_(score) {}
string get_class_id() const { return class_id_; }
int get_score() const { return score_; }
private:
string class_id_;
int score_;
};
// 定义Teacher类,继承自Person类
class Teacher : public Person {
public:
Teacher(string id, string name, string title, string department) : Person(id, name), title_(title), department_(department) {}
string get_title() const { return title_; }
string get_department() const { return department_; }
private:
string title_;
string department_;
};
// 输入学生数据
vector<Student> input_students() {
vector<Student> students;
while (true) {
string id, name, class_id;
int score;
cout << "请输入学生学号(输入q结束输入):";
cin >> id;
if (id == "q") {
break;
}
cout << "请输入学生姓名:";
cin >> name;
cout << "请输入学生班级:";
cin >> class_id;
cout << "请输入学生成绩:";
cin >> score;
Student student(id, name, class_id, score);
students.push_back(student);
}
return students;
}
// 输入教师数据
vector<Teacher> input_teachers() {
vector<Teacher> teachers;
while (true) {
string id, name, title, department;
cout << "请输入教师编号(输入q结束输入):";
cin >> id;
if (id == "q") {
break;
}
cout << "请输入教师姓名:";
cin >> name;
cout << "请输入教师职称:";
cin >> title;
cout << "请输入教师所在部门:";
cin >> department;
Teacher teacher(id, name, title, department);
teachers.push_back(teacher);
}
return teachers;
}
// 显示学生数据
void show_students(const vector<Student>& students) {
cout << "学生数据:" << endl;
for (const auto& student : students) {
cout << "学号:" << student.get_id() << ",姓名:" << student.get_name()
<< ",班级:" << student.get_class_id() << ",成绩:" << student.get_score() << endl;
}
}
// 显示教师数据
void show_teachers(const vector<Teacher>& teachers) {
cout << "教师数据:" << endl;
for (const auto& teacher : teachers) {
cout << "编号:" << teacher.get_id() << ",姓名:" << teacher.get_name()
<< ",职称:" << teacher.get_title() << ",部门:" << teacher.get_department() << endl;
}
}
// 主函数
int main() {
vector<Student> students = input_students();
vector<Teacher> teachers = input_teachers();
show_students(students);
show_teachers(teachers);
return 0;
}
```
这段代码定义了一个`Person`类作为`Student`和`Teacher`类的基类,分别表示学生和教师信息。在输入学生和教师信息时,我们通过`cin`函数获取用户输入,并将输入内容传入相应的类的构造函数中创建对象。最后,我们通过`cout`函数输出学生和教师的信息。
阅读全文