c++ - 在派生构造函数中访问基本成员时出现问题

标签 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
    };
};

我在指示的位置遇到编译错误:

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/

相关文章:

c# - 如何从此数组中检索信息?

c++ - 为什么我从继承自 QAbstractListModel 的类中得到 "use of delete function"?

Java,如何从抽象类继承方法

接口(interface)中方法的java泛型类型参数

hibernate - 在 SELECT 中使用构造函数表达式的 JPQL/Hibernate 限制

c++ - 新手程序员。酒吧填充游戏

c++ - 在我为我的二维 vector 赋予第一个值后控制台关闭

perl - 我应该在编译时而不是运行时建立继承,如果是,为什么?

javascript - Setter/Getter 对此

c++ - 如何解决有关迭代器构造函数的一系列错误,涉及预期左值、缺少转换和可行性