问题描述
我有以下代码:
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
是指派生类型可以访问它自己的基类的成员而不是任何随机对象. 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.
这篇关于无法访问派生类中的基类的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!