Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

c++ - Problem accessing base member in derived constructor

Given the following classes:

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'.

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.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...