Hello,
I'm having problem using iterator.
I have a class named Matrix and other one named BinPacking. I'm trying to manipulate the matrix in the BinPacking class, where i have a vector of objects of matrix class.
class Matrix
{
private:
int cdMatrix;//code
int rowMatrix;//row
int colMatrix;//column
protected:
vector<vector<int> > mymatrix;
public:
Matrix(int,int,int);//build the matrix here
~Matrix();
};
class BinPacking: public Matrix
{
private:
vector<Matrix> matrixOBJ;
public:
BinPacking(const string&);
~BinPacking();
void writeFiles()
{
ofstream f_FF_out("FF.txt");
for(vector<Matrix>::iterator itOBJ = matrixOBJ.begin();
itOBJ != matrixOBJ.end(); ++itOBJ)
{
for(vector<vector<int> >::iterator itrow = itOBJ->mymatrix.begin();
itrow != itOBJ->mymatrix.end(); ++itrow)
{
for(vector<int>::iterator itcol = itrow->begin();
itcol != itrow->end(); ++itcol)
{
f_FF_out << *itcol;
}
f_FF_out << endl;
}
f_FF_out << endl;
}
}
};
The error is on line 31 and 32 : C2248: 'Matrix::mymatrix' : cannot access protected member declared in class 'Matrix' and also IntelliSense: protected member "Matrix::mymatrix" is not accessible through a "Matrix" pointer or object
My vector of vectors mymatrix probably need to be a reference or a pointer? I'm kind newbie , so sorry if i'm doing anything stupid. But can somebody help me out?
The reason you are getting this error is because you set the field mymatrix to be protected. This means outside of the Matrix class (or one of its subclasses), you cannot access that field, and hence you can't get an iterator from it. Quick and dirty solution: make it public. However there are good reasons why you should sometimes make members protected/private, and the way you have written the class as it stands is sensible with regard to public/private access, but getting around this the 'correct' way is a bit of a challenge, so for your purposes making it public is probably fine. For a good discussion of why private/protected fields are necessary, google encapsulation (maybe restrict it to c++, but the concept exists in other programming languages).
thank you guys, it worked with i put it public. I thought i could manipulate a protected member with inheritances, maybe with iterators and vectors are different.
You can access a protected member from an inherited class, but only it's own members. In your example, the BinPacking class contains a member called mymatrix, which it can manipulate. This does not mean that you can manipulate the mymatrix field inside any Matrix objects. I think you've kind of misunderstood how inheritance works, this example does not use it correctly. I would definitely recommend reading up on it more as it is an important concept.