上篇文章,我们介绍了【c++】通过类中嵌入结构体实现简单数据库,今天。我们就来讲一个案例
下面是一个简单的示例,展示了如何在C++中定义一个包含结构体的类,并在该类中实现基本的CRUD操作。我们将创建一个Student结构体来存储学生的信息,并在StudentDatabase类中实现对学生信息的增删改查功能。
源码:
#include <iostream>
#include <vector>
#include <string>
#include<algorithm>
// 定义学生信息的结构体
struct Student {
int id;
std::string name;
int age;
// 构造函数
Student(int id, std::string name, int age) : id(id), name(name), age(age) {}
};
// 定义学生数据库类
class StudentDatabase {
private:
std::vector<Student> students; // 使用vector来存储学生信息
public:
// 增加学生信息
void addStudent(int id, std::string name, int age) {
// 这里简单起见不检查ID是否重复
students.push_back(Student(id, name, age));
}