Cannot access protected member of base class in derived class

后端 未结 4 767
渐次进展
渐次进展 2021-01-07 19:01

I have the following code:

struct A {
protected:
    A() {}

    A* a;
};

struct B : A {
protected:
    B() { b.a = &b; }

    A b;
};

4条回答
  •  Happy的楠姐
    2021-01-07 19:09

    The meaning of protected is that the derived type will have access to that member of its own base and not of any random object*. In your case, you care trying to modify b's member which is outside of your control (i.e. you can set this->a, but not b.a)

    There is a hack to get this to work if you are interested, but a better solution would be to refactor the code and not depend on hacks. You could, for example, provide a constructor in A that takes an A* as argument (this constructor should be public) and then initialize it in the initializer list of B:

    A::A( A* p ) : a(p) {}
    B::B() : b(&b) {}
    

    * protected grants you access to the base member in any instance of your own type or derived from your own type.

提交回复
热议问题