C++:创建指向类对象的向量

C++: Creating a vector that points to a class object

本文关键字:对象 向量 创建 C++      更新时间:2023-10-16

我有以下学生类,它创建一个学生,然后允许我将该学生存储在学生类向量中。我现在想要一个课程向量,它允许每个学生都有自己的课程分组。我希望这些课程指向拥有它们的学生,以便当学生从学生列表中删除时,他们的课程也会随之删除。理想情况下,我希望将此课程矢量作为学生班级的私人成员,以便只有在指定拥有这些课程的特定学生时才能访问/更改这些课程。

主要:

#include <iostream>
#include <string>
#include "student.h"
#include "students.h"
using namespace std;

int main(){
  Students stuList;
  Student* bob = new Student ("Bob" "Jones" 10000909);
  stuList.add(bob); 
  return 0;
}

学生 h:

#include <ostream>
#include <string>  
class Student {
    public:
    Student::Student(const string & FName, const string & LName, const int ID);
    private:
    string first;
    string last;
    int id;
};

学生 H:

#include <ostream>
#include <vector>
#include "student.h"
#include <string>
using namespace std;
class Students {
    public:
    Students(); 
    void add(Student & aStudent);
    private:
    vector<Student*> collection;
};

一段时间以来,我一直在想办法实现这一目标,但我正在画一个空白。任何建议/提示将不胜感激。

在学生类中,您可以添加一个包含学生拥有的课程的向量,还可以添加一个包含学生拥有的课程组的向量:

class Student {
   ...
   vector<Course*> ownedCourses;
   vector<Course*> attendedCourses;
};

然后在您的班级课程中,您将需要一个包含本课程所有服务员的向量:

class Course {
    ...
    vector<Student*> attendants;
};

如果您现在从列表中删除了一个发育障碍,您还将从其他学生的列表中拥有他拥有的所有课程:

vector<Course*> ownedCourses = studentToRemove.getOwnedCourses();
for (const Course* course : ownedCourses)
{  
    vector<Student*> attendants = course->getStudents();
    for(const Student* student : attendants) {
        student->removeAttendedCourse(course);
    }
}