用c++类编写学生选课系统程序
时间: 2023-08-28 08:06:49 浏览: 121
c++编写的学生选课系统
3星 · 编辑精心推荐
好的,我可以为您提供一个简单的学生选课系统程序。首先,我们需要定义一个学生类(Student),包含学生的基本信息和已选课程信息,代码如下:
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
string major;
vector<string> courses; // 已选课程
public:
Student(string name, int age, string major)
: name(name), age(age), major(major) {}
void setName(string name) { this->name = name; }
void setAge(int age) { this->age = age; }
void setMajor(string major) { this->major = major; }
string getName() const { return name; }
int getAge() const { return age; }
string getMajor() const { return major; }
vector<string> getCourses() const { return courses; }
void addCourse(string course) { courses.push_back(course); }
};
```
下一步,我们需要定义一个课程类(Course),包含课程的基本信息和已选学生信息,代码如下:
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Course {
private:
string name;
string teacher;
int capacity; // 课程容量
vector<Student*> students; // 已选学生
public:
Course(string name, string teacher, int capacity)
: name(name), teacher(teacher), capacity(capacity) {}
void setName(string name) { this->name = name; }
void setTeacher(string teacher) { this->teacher = teacher; }
void setCapacity(int capacity) { this->capacity = capacity; }
string getName() const { return name; }
string getTeacher() const { return teacher; }
int getCapacity() const { return capacity; }
vector<Student*> getStudents() const { return students; }
bool addStudent(Student* student) {
if (students.size() >= capacity) {
return false; // 课程已满,选课失败
}
students.push_back(student);
student->addCourse(name);
return true; // 选课成功
}
};
```
最后,我们可以编写一个简单的选课系统程序,代码如下:
```cpp
#include <iostream>
#include "Student.h"
#include "Course.h"
using namespace std;
int main() {
// 创建学生和课程
Student* s1 = new Student("Tom", 18, "Computer Science");
Student* s2 = new Student("Jerry", 19, "Math");
Course* c1 = new Course("C++ Programming", "John", 2);
Course* c2 = new Course("Data Structures", "Mike", 1);
// 学生选课
bool success = c1->addStudent(s1);
if (success) {
cout << s1->getName() << " selected " << c1->getName() << endl;
} else {
cout << "Selection failed." << endl;
}
success = c1->addStudent(s2);
if (success) {
cout << s2->getName() << " selected " << c1->getName() << endl;
} else {
cout << "Selection failed." << endl;
}
success = c2->addStudent(s1);
if (success) {
cout << s1->getName() << " selected " << c2->getName() << endl;
} else {
cout << "Selection failed." << endl;
}
// 输出学生的选课信息
vector<string> courses = s1->getCourses();
cout << s1->getName() << " selected courses: ";
for (string course : courses) {
cout << course << " ";
}
cout << endl;
courses = s2->getCourses();
cout << s2->getName() << " selected courses: ";
for (string course : courses) {
cout << course << " ";
}
cout << endl;
// 释放内存
delete s1;
delete s2;
delete c1;
delete c2;
return 0;
}
```
这个程序可以让学生选课,并输出学生的选课信息。当课程已满时,选课失败。同时,这个程序还考虑了内存释放问题,避免了内存泄漏。
阅读全文