C++:创建指向类对象的向量
C++: Creating a vector that points to a class object
我有以下学生类,它创建一个学生,然后允许我将该学生存储在学生类向量中。我现在想要一个课程向量,它允许每个学生都有自己的课程分组。我希望这些课程指向拥有它们的学生,以便当学生从学生列表中删除时,他们的课程也会随之删除。理想情况下,我希望将此课程矢量作为学生班级的私人成员,以便只有在指定拥有这些课程的特定学生时才能访问/更改这些课程。
主要:
#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);
}
}
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?