Leo*_*Hat 4 c++ inheritance constructor
鉴于以下课程:
class Foo
{
struct BarBC
{
protected:
BarBC(uint32_t aKey)
: mKey(aKey)
mOtherKey(0)
public:
const uint32_t mKey;
const uint32_t mOtherKey;
};
struct Bar : public BarBC
{
Bar(uint32_t aKey, uint32_t aOtherKey)
: BarBC(aKey),
mOtherKey(aOtherKey) // Compile error here
};
};
Run Code Online (Sandbox Code Playgroud)
我在指出的位置收到编译错误:
error: class `Foo::Bar' does not have any field named `mOtherKey'.
Run Code Online (Sandbox Code Playgroud)
有谁能解释一下?我怀疑这是一个语法问题,因为我的Bar类在类中定义Foo,但似乎无法找到解决方法.
这是简单的公共继承,因此mOtherKey应该可以从Bar构造函数中访问.对?
或者它是与mOtherKeyconst 这个事实有关,我已经0在BarBC构造函数中初始化它了?
您不能通过成员初始化列表初始化基类的成员,只能直接和虚拟基类以及类本身的非静态数据成员.
将其他参数传递给基类的构造函数:
struct BarBC {
BarBC(uint32_t aKey, uint32_t otherKey = 0)
: mKey(aKey), mOtherKey(otherKey)
{}
// ...
};
struct Bar : public BarBC {
Bar(uint32_t aKey, uint32_t aOtherKey)
: BarBC(aKey, aOtherKey)
{}
};
Run Code Online (Sandbox Code Playgroud)