这个程序中,我们定义了一个 `Teacher` 类,它有三个属性,分别是教师的姓名、年龄和所在院系,还定义了一个 `show()` 方法来显示教师信息。
然后,我们在 `main()` 函数中定义了一个指针数组 `teachers`,用来存放教师对象。程序中提供了三个功能,分别是添加教师信息、查找教师信息和显示所有教师信息。在添加教师信息时,我们使用 `new` 运算符动态分配内存来创建 `Teacher` 对象,并将其添加到数组中。在查找教师信息时,我们使用一个 `for` 循环遍历数组,查找指定姓名的教师对象,如果找到则调用 `show()` 方法显示教师信息。在显示所有教师信息时,我们同样使用一个 `for` 循环遍历数组,调用每个教师对象的 `show()` 方法来显示信息。
最后,在程序退出前,我们使用 `delete` 运算符释放所有动态分配的内存,避免内存泄漏。
希望这个程序可以帮助你理解如何使用 C++ 实现教师管理系统。
#include <iostream>
#include <string>
using namespace std;
// 定义教师类
class Teacher {
public:
string name; // 姓名
int age; // 年龄
string department; // 所在院系
// 构造函数
Teacher(string name, int age, string department) {
this->name = name;
this->age = age;
this->department = department;
}
// 显示教师信息
void show() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Department: " << department << endl;
}
};
// 添加教师信息
void add_teacher(Teacher *teachers[], int &count) {
if (count < 10) {
string name, department;
int age;
cout << "Enter teacher name: ";
cin >> name;
cout << "Enter teacher age: ";
cin >> age;
cout << "Enter teacher department: ";
cin >> department;
Teacher *teacher = new Teacher(name, age, department);
teachers[count] = teacher;
count++;
cout << "Teacher information added successfully." << endl;
} else {
cout << "Cannot add more teachers. Maximum limit reached." << endl;
}
}
// 查找教师信息
void find_teacher(Teacher *teachers[], int count) {
string name;
cout << "Enter teacher name to search: ";
cin >> name;
for (int i = 0; i < count; i++) {
if (teachers[i]->name == name) {
cout << "Teacher information found." << endl;
teachers[i]->show();
return;
}
}
cout << "Teacher not found." << endl;
}
// 显示所有教师信息
void show_teachers(Teacher *teachers[], int count) {
for (int i = 0; i < count; i++) {
teachers[i]->show();
cout << endl;
}
}
int main() {
int option, count = 0;
Teacher *teachers[10]; // 教师数组,最多存放10个教师
do {
cout << "===== Teacher Management System =====" << endl;
cout << "1. Add teacher information" << endl;
cout << "2. Find teacher information" << endl;
cout << "3. Show all teachers' information" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> option;
switch (option) {
case 1:
add_teacher(teachers, count);
break;
case 2:
if (count > 0) {
find_teacher(teachers, count);
} else {
cout << "No teachers found." << endl;
}
break;
case 3:
if (count > 0) {
show_teachers(teachers, count);
} else {
cout << "No teachers found." << endl;
}
break;
case 4:
cout << "Exiting program..." << endl;
break;
default:
cout << "Invalid option. Please enter a valid option (1-4)." << endl;
}
} while (option != 4);
// 释放动态分配的内存
for (int i = 0; i < count; i++) {
delete teachers[i];
}
cout << "Memory released." << endl;
return 0;
}