World.cpp:
World::World() {
//something
}
World::~World() {
//something
}
void World::doSomething(Organism *organisms[20][20]) {
cout << organisms[1][1]->Key(); // example of what I need to do here
}
int main() {
World *world = new World();
World::doSomething(world->organisms);
return 0;
}
world.h
class World {
public:
static void doSomething(Organism *organisms[20][20]);
World();
~World();
Organism *organisms[20][20];
};
Organism.cpp
Organism::Organism(){
}
Organism::~Organism(){
}
char Organism::Key(){
return this->key;
}
Organism.h
class Organism {
public:
Organism();
~Organism();
// ...
char Key();
protected:
char key;
// ...
};
I need to make something like a machine, creating animals. The code above works very good, to let you know: the array organisms is an array of pointers to specific organisms of type Organism, every organism contains it's char key value. My problem is that I need to make the Organism *organisms array protected or private instead of public. And there begin problems.
I have an error that I cannot access the protected member of declared in World in file World.cpp line with doSomething ( underlined organisms ).
I tried using friend etc. but none of the methods worked. Any idea how to access this array from main? (function parameters can be changed, the array need to be protected/private) Any simple method how to do this?
Thanks for help
Problem is that main() is in the global space, and it is not a class. So it cannot be the friend of the class which has private members. Your best bet is to make another class which will be the friend of your class and use that class access the private members.
You can indeed make the
main
function a friend of a class like so:However, why not just make
doSomething
a non-static member function?