在派生构造函数中访问基本成员时出现问题 [英] Problem accessing base member in derived constructor

查看:145
本文介绍了在派生构造函数中访问基本成员时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类:

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

我在指示的点收到编译错误:

I am getting a compilation error at the point indicated:

error: class `Foo::Bar' does not have any field named `mOtherKey'.

任何人都可以解释一下吗?我怀疑这是一个语法问题,因为我的 Bar 类被定义在 Foo 类中,找到一个方法。

Can anyone explain this? I suspect it's a syntactical problem due to my Bar class being defined within the Foo class, but can't seem to find a way around it.

这是简单的公共继承,所以 mOtherKey 应该可以从 Bar 构造函数。是吗?

This is simple public inheritance, so mOtherKey should be accessible from the Bar constructor. Right?

或者是与 mOtherKey 是const并且我已经初始化它的事实 0 BarBC 构造函数中?

Or is it something to do with the fact that mOtherKey is const and I have already initialised it to 0 in the BarBC constructor?

推荐答案

您不能通过成员初始化器列表初始化基类的成员,只能通过类本身的直接和虚拟基类和非静态数据成员。

传递其他参数到基类的构造函数:

You can't initialize members of a base class through a member initializer list, only direct and virtual base classes and non-static data members of the class itself.
Pass additional parameters to the base class' constructor instead:

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)
    {}
};

这篇关于在派生构造函数中访问基本成员时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆