写的太简单了,有更复杂的案例代码吗
时间: 2024-04-17 13:26:12 浏览: 12
当然!以下是一个稍微复杂一些的C++案例代码,展示了一个简单的学生管理系统:
```cpp
#include <iostream>
#include <vector>
#include <string>
class Student {
private:
std::string id;
std::string name;
std::string major;
public:
Student(std::string id, std::string name, std::string major) {
this->id = id;
this->name = name;
this->major = major;
}
std::string getId() {
return id;
}
std::string getName() {
return name;
}
std::string getMajor() {
return major;
}
void displayInfo() {
std::cout << "ID: " << id << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Major: " << major << std::endl;
}
};
class StudentManagementSystem {
private:
std::vector<Student> students;
public:
void addStudent(Student student) {
students.push_back(student);
std::cout << "Student added successfully!" << std::endl;
}
void displayAllStudents() {
if (students.empty()) {
std::cout << "No students found." << std::endl;
} else {
for (int i = 0; i < students.size(); i++) {
students[i].displayInfo();
std::cout << "---------------------" << std::endl;
}
}
}
void searchStudentById(std::string id) {
bool found = false;
for (int i = 0; i < students.size(); i++) {
if (students[i].getId() == id) {
students[i].displayInfo();
found = true;
break;
}
}
if (!found) {
std::cout << "Student not found." << std::endl;
}
}
};
int main() {
Student student1("001", "John Doe", "Computer Science");
Student student2("002", "Jane Smith", "Mathematics");
StudentManagementSystem sms;
sms.addStudent(student1);
sms.addStudent(student2);
sms.displayAllStudents();
std::cout << "Search student by ID: ";
std::string searchId;
std::cin >> searchId;
sms.searchStudentById(searchId);
return 0;
}
```
这个案例代码实现了一个简单的学生管理系统,可以添加学生、显示所有学生和通过ID搜索学生。希望你喜欢!