简体   繁体   中英

Child class inherit friendship

I have a class State and another friend class Game. My question is, if I have a class MenuState which extends State, is MenuState a friend of Game as well?

EDIT:

So if I have a situation like this:

class Game
{
    private:
        StateManager* myStateManager = new StateManager();
}

class State
{
    public:
        static void create(StateManager* Parent, const std::string name) {};

    private:
        StateManager* parent;
}

#define DECLARE_STATE_CLASS(T)                                   \
static void create(StateManager* Parent, const std::string name) \
{                                                                \
        T* myState = new T();                                    \
        myState->parent = Parent;                                \
        Parent->manageState(name, myState);                      \
}                                                                \

class MenuState : State
{
    public:
        DECLARE_STATE_CLASS(MenuState)
}

int main()
{
    Game app;
    MenuState::create(This needs to be the stateManager in app, "MenuState");
    app.init("MenuState");
}

How can I make this work without making the state manager public?

So if the situation is like the following

class Game {
  friend class State;
}

class State {

}

class MenuState : public State {

}

Then the answer is no, as friend directive is not implicitly inherited. And I don't see why it should be inherited, Game explicitly allows State to access its internal implementation details but why this should be extended to subclasses of State which could do different things?

You can add an access function to Game. Even if MenuState is a friend of Game, this still won't work, since you are trying to pass Game's private member, not access it inside the function.

If for instance, you have no right to modify Game, then the choice would be to add an access function inside State, and then you can use that access function from MenuState.

class State
{
    public:
    static void create(StateManager* Parent, const std::string name) {};
    StateManager* getManager(Game* g){
        return g->myStateManager;
    }

    private:
    StateManager* parent;
}

#define DECLARE_STATE_CLASS(T)                                   \
static void create(Game* g, const std::string name) \
{                                                                \
        T* myState = new T();                                    \
        myState->parent = State::getManager(g);                              \
        Parent->manageState(name, myState);                      \
}                                                                \

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM