Domanda

Here is the compiler error I received.

project1.cc: In function std::vector<Enrollment, std::allocator<Enrollment> > returnCourseEnrollment(int)': project1.cc:84: error:Course Enrollment::course' is private

project1.cc:293: error: within this context

my code:

290     vector<Enrollment> e;
291     for (int i=0; i<Enrollment::enrollmentList.size();i++) {
292         Enrollment enroll = Enrollment::enrollmentList[i];
293         if (enroll.course.getCourseID()) e.push_back(enroll);
294     }

I am searching through a vector to match a course ID with the students in the course.

231             string myText(line);
232             istringstream iss(myText);
233             if (!(iss>>id)) id = 0;
234             iss.ignore(1,',');
235             if (!(iss>>id2)) id2 = 0;
236             cout<<"id: "<<id<<" id2: "<<id2<<endl;
237             Enrollment newEnrollment(Student::studentList[id],Course::courseList[id2]);
238             Enrollment::enrollmentList[i] = newEnrollment;
239             i++;

Here is where the vector is made. As you can see each element of he vector is occupied by an instance to a class. Any recommendations on how I can gain access to the private attributes in the method I am making?

edit: here is the enrollment class

 82     private:
 83         Student student;
 84         Course course;
 85
 86     public:
 87         Enrollment(Student student,Course course):student(student),course(course){}
 88         Enrollment(){}
 89         static vector<Enrollment> enrollmentList;
 90         static int loadEnrollment();
 91         static vector<Enrollment> returnCourseEnrollment(int courseid);
 92         static vector<Enrollment> returnSchedule(int studentid);
 93         friend ostream& operator<< (ostream& out,Enrollment e) {
 94             out<<e.student.getName()<<"("<<e.student.getId()<<")"<<e.course.getName()<<"("<<e.course.getId()<<")";
 95             return out;
È stato utile?

Soluzione

Suspect you have something like:

class Enrollment
{
    // ...
    Course course;
};

you should ensure that course member appears in a public class section to be accessible as follows:

class Enrollment
{
public:
    Course course;
};

Another option is to declare the returnCourseEnrollment() function to be a friend of Enrollment:

class Enrollment;

class Enrollment
{
private:
    friend std::vector<Enrollment, std::allocator<Enrollment> > 
               returnCourseEnrollment(int);
    Course course;
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top