给定以下类:
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
};
};
我在指示的位置遇到编译错误:
error: class `Foo::Bar' does not have any field named `mOtherKey'.
谁能解释一下?我怀疑这是一个语法问题,因为我的 Bar
类是在 Foo
类中定义的,但似乎找不到解决方法。
这是简单的公共(public)继承,因此 mOtherKey
应该可以从 Bar
构造函数访问。对吧?
或者这与 mOtherKey
是 const 并且我已经在 BarBC
构造函数中将其初始化为 0
有关吗?
最佳答案
不能通过成员初始化列表初始化基类的成员,只能通过直接和虚拟基类以及类本身的非静态数据成员。
而是将附加参数传递给基类的构造函数:
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)
{}
};
关于c++ - 在派生构造函数中访问基本成员时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947583/