更新时间:2023-02-14 23:28:40
protected
的含义是派生类型将有权访问自己的基类成员而不是任何随机对象*.在您的情况下,您关心尝试修改超出您控制范围的 b
成员(即您可以设置 this->a
,但不能设置 ba
)
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
)
如果您有兴趣,可以使用 hack 来使其工作,但更好的解决方案是重构代码而不是依赖于 hack.例如,您可以在 A
中提供一个构造函数,它接受一个 A*
作为参数(这个构造函数应该是公共的),然后在 A*
的初始化列表中初始化它>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.