无法访问派生类中基类的受保护成员 [英] Cannot access protected member of base class in derived class
问题描述
我有以下代码:
struct A {
protected:
A() {}
A* a;
};
struct B : A {
protected:
B() { b.a = &b; }
A b;
};
奇怪的是它不能编译.罪魁祸首是 ba = &b;
赋值:GCC 和 clang 都抱怨 A()
受到保护,这应该不是问题,因为 B 继承了 A.我进入了标准的哪个阴暗角落?
It strangely doesn't compile. The culprit is the b.a = &b;
assignment: both GCC and clang complain that A()
is protected, which shouldn't be a problem because B inherits A. Which dark corner of the standard have I come into?
推荐答案
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.
这篇关于无法访问派生类中基类的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!