3

在课堂上,我有一组科目。我想通过这个集合并在每个主题上调用一个将学生添加到该主题的函数。这是我的功能的外观。

void Faculty::addStudent(Student* n) {
    this->Students.insert(n);
    set<Subject*>::iterator it;

    for(it = this->Subjects.begin(); it != this->Subjects.end(); it++) {
        (*it)->addStudent(n);
    }
}

问题是我得到一个错误:

Unhandled exception at 0x01341c6d in University.exe: 0xC0000005: Access violation reading location 0x1000694d.

我正在使用 Microsoft Visual 2010。

我是 C++ 新手。

我可以提供任何其他必要的信息,只是不知道是哪个。请告诉我是否需要什么。

class Student: public Human {
    friend class University;
    friend class Faculty;
    friend class Subject;
public:
    Student(string name, string surname);
    ~Student();
    void Index(int n);
private:
    int index;
};
4

1 回答 1

10

在大多数情况下,更好的做法是在两个或多个类之间共享数据时使用智能指针而不是原始数据指针。

例子。首先,我们像这样包装指针:

typedef shared_ptr<Student> StudentSPtr;
typedef shared_ptr<Subject> SubjectSPtr;

在此之后,我们在整个代码中用这些指针(StudentSptr n而不是)替换原始指针。Student* n因此,您的函数可能如下所示:

void Faculty::addStudent(StudentSptr n){
  this->Students.insert(n);
  vector<SubjectSPtr>::iterator it;  //in your case vector is more proper, I think

  for(it = this->Subjects.begin(); it != this->Subjects.end(); it++){
    (*it)->addStudent(n);
    }
}
于 2012-06-14T11:30:45.377 回答