Accessing protected members of class from main

≡放荡痞女 提交于 2019-12-24 01:03:49

问题


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


回答1:


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?




回答2:


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.



来源:https://stackoverflow.com/questions/23231789/accessing-protected-members-of-class-from-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!