更新时间:2023-02-14 23:15:38
protected
是指派生类型可以访问它自己的基类的成员而不是任何随机对象 * 。在你的情况下,你在尝试修改不受你控制的 b
的成员(即你可以设置 this-> a
,但不是
ba
)
The meaning of protected
is that the derived type will have access to that member of it's 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
)
感兴趣,但更好的解决方案是重构代码,而不依赖于hack。例如,您可以在 A
中提供一个构造函数,它以 A *
作为参数(此构造函数应为public ),然后在 B
的初始化器列表中初始化它:
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
您自己类型的任何实例中的基础成员或派生自您自己的类型。
*protected
grants you access to the base member in any instance of your own type or derived from your own type.