Accessing parent's protected variables

前端 未结 4 2027
夕颜
夕颜 2020-12-03 17:03

I couldn\'t think of a better wording for the title, so it is a little misleading, however, I am not talking about a child accessing its variables inherited from its parent,

4条回答
  •  被撕碎了的回忆
    2020-12-03 17:30

    This is so easy (meaning the apparent misunderstanding of the OP, is because people aren't taking the time to read the OP).

    You simply make the child a friend of the parent's variable that you need to access.

    Or, you can make the child a friend of the parent class.

    That way any child has access to any parent's member variables, exactly the way you are expecting.

    class Child;
    
    class Parent {
      protected:
         Parent *target;
         int hp;
         friend void Child::my_func();
    }
    
    class Child : public Parent {
      public:
         void my_func();
    }
    
    void Child::my_func() {
        target->hp -= 50;
    }
    

    The downside to this is that EVERY child can have access to the variables of EVERY parent. However, you must consider that in your case, the compiler cannot know that Parent *target is the same instance as the child. Given that you named it target, I would expect that having EVERY child have access to variables of EVERY parent is what you want.

    Here's another possibility. Have everyone else use an interface to access the parent, and have only your child use the actual parent class. The result is the same though. Every child has access to every parents variables.

    You're confusing class with instance. The child has access to the same member variables of the base class that is of the same INSTANCE.

提交回复
热议问题