C + +写一个学生管理系统
时间: 2023-06-29 14:06:17 浏览: 57
学生管理系统是一个非常常见的小项目,可以用来练习C++面向对象编程的基本技巧。下面是一个简单的实现示例:
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
Student() { }
Student(const string& name, const string& id, int age) :
name_(name), id_(id), age_(age) { }
const string& GetName() const { return name_; }
const string& GetID() const { return id_; }
int GetAge() const { return age_; }
void SetName(const string& name) { name_ = name; }
void SetID(const string& id) { id_ = id; }
void SetAge(int age) { age_ = age; }
private:
string name_;
string id_;
int age_;
};
class StudentManager {
public:
StudentManager() { }
~StudentManager() { }
void AddStudent(const Student& s) {
students_.push_back(s);
}
void RemoveStudent(const string& id) {
for (auto iter = students_.begin(); iter != students_.end(); ++iter) {
if (iter->GetID() == id) {
students_.erase(iter);
return;
}
}
}
void ListStudents() const {
for (const auto& s : students_) {
cout << "Name: " << s.GetName() << ", ID: " << s.GetID() << ", Age: " << s.GetAge() << endl;
}
}
private:
vector<Student> students_;
};
int main() {
Student s1("Alice", "001", 20);
Student s2("Bob", "002", 21);
Student s3("Charlie", "003", 22);
StudentManager sm;
sm.AddStudent(s1);
sm.AddStudent(s2);
sm.AddStudent(s3);
sm.ListStudents();
sm.RemoveStudent("002");
sm.ListStudents();
return 0;
}
```
这个示例中,我们定义了两个类:`Student` 和 `StudentManager`。`Student` 表示一个学生,包含姓名、学号和年龄三个属性,以及相应的访问器和修改器。`StudentManager` 表示学生管理器,包含添加、删除和列出学生三个方法,以及一个学生列表。
在 `main` 函数中,我们创建了三个学生对象,并将它们添加到学生管理器中。然后我们列出了所有的学生,并删除了一个学生。最后再列出所有的学生,可以看到已经删除了其中一个。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)