Accessing parent's protected variables

前端 未结 4 2026
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 17:48

    Member functions of a particular class only have access to protected members of base classes that actually are base class subobjects of objects of their own class type (or more derived types).

    Members of one class do not have access to protected members of other instances of that base class and so are also forbidden from accessing protected members through a reference or pointer to the base class type even if at runtime that pointer or reference might be to an object that is of the type of the class whose member function is attempting the access. Access control is enforced at compile time.

    E.g.

    class X
    {
    protected:
        int z;
    };
    
    class Y : X
    {
    public:
        int f( const Y& y )
        {
            return y.z; // OK
        }
    
        int g( const X& x )
        {
            return x.z; // Error, Y::g has no access to X::z
        }
    };
    

    In your example, in the expression target->hp, the access to target is legal because you are accessing a member of the current object (which has the type of the class of which the function is a member, Child), but the access to the member hp is not legal because the type of target is not a pointer to Child, but a pointer to Parent.

提交回复
热议问题