Reputation: 706
I encountered this problem when implementing a class:
class Cell {
bool isAlive;
int numNeighbours;
//...omit irrelavent private members
public:
Cell(); // Default constructor
~Cell(); // Destructor
void setLiving();
....
};
void Cell::setLiving(){
isAlive=true;
}
class Grid{...
friend std::ostream& ::operator(std::ostream& out, const Grid &g);
};//...omit
std::ostream& ::operator<<(std::ostream &out, const Grid &g){
int i,j;
for(i=0;i<g.gridSize;i++){
for(j=0;j<g.gridSize;j++){
if(**g.theGrid[i][j].isAliv*e*) out<<"X";
else out<<"_";
}
out<<endl;
}
return out;
}
The complier said that "isAlive" is a private member so I can't call it that way I think the problem is at "g.theGrid[i][j].isAlive" I tried to friend class Grid but it didnt help
Upvotes: 0
Views: 258
Reputation: 3351
This line
if(**g.theGrid[i][j].isAlive) out<<"X"
Is accessing the private member 'isAlive'. I assume theGrid is a two dimensional array of Cell objects. You need a getLiving() method defined. Then use it here.
Upvotes: 0
Reputation: 1569
isAlive is private, declare it as public...
EDIT1:
class Cell {
public:
bool isAlive;
Update:
Upvotes: -1
Reputation: 101
The class member isAlive is private, so the operator didn't have the right to access it, you need to put a friend declaration in the body of Cell's definition.
class Cell {
friend std::ostream& operator<<(std::ostream&, const Cell&);
// ...
};
Upvotes: 0
Reputation: 129764
You mentioned operator<<
— it's most likely a free function, so it needs to be declared as friend
to be able to access private members.
class Cell {
friend std::ostream& operator<<(std::ostream&, const Grid&);
// ...
};
Upvotes: 4