Accessing protected members of class from main

2019-07-20 20:18发布

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

2条回答
Summer. ? 凉城
2楼-- · 2019-07-20 20:34

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.

查看更多
相关推荐>>
3楼-- · 2019-07-20 20:46

You can indeed make the main function a friend of a class like so:

int main(int, char**);

namespace N {
    struct C {
        friend int ::main(int, char**);

    private:
        int privateer = 42;
    };
}

int main(int, char**) {
    ::std::cout << N::C().privateer << "\n";
}

However, why not just make doSomething a non-static member function?

查看更多
登录 后发表回答