在嵌套类中无效使用非静态数据成员

时间:2017-03-26 02:24:45

标签: c++ class

我正在编写一些代码,其中包含来自基类的两个类的多态继承,这些类都嵌套在类中,如下所示:

#include <iostream>

using namespace std;

class A
{

    class base
    {
    public:
        virtual void foo();
    };

    class B: public base
    {
    public:
        void foo() { cout << number1; }
    };

    class C: public base
    {
    public:
        void foo() { cout << number2; }
    };

public:
    A(unsigned num): number1(num), number2(num*2)
    {
        if(num < 5)
        {
            a = new B;
        }
        else
        {
            a = new C;
        }
    }

    void getNumber() const
    {
        a->foo();
    }

private:
    const unsigned number1;
    const unsigned number2;

    base* a;
};

int main()
{
    A object1(1);
    A object2(10);

    object1.getNumber();
    object2.getNumber();
}

根据我对c ++ 11及其前瞻的理解,这应该是可能的吗?我知道c ++ 11后的嵌套类可以访问它们嵌套在其中的类的数据成员,只要它们有权访问它,但这似乎与此相反。当我编译它时,我得到这些错误:

compiler commands: g++ -std=c++14 test.cpp -o t.exe

test.cpp: In member function 'virtual void A::B::foo()':
test.cpp:17:34: error: invalid use of non-static data member 'A::number1'
             void foo() { cout << number1; }
                              ^
test.cpp:45:24: note: declared here
         const unsigned number1;
                    ^
test.cpp: In member function 'virtual void A::C::foo()':
test.cpp:23:34: error: invalid use of non-static data member 'A::number2'
             void foo() { cout << number2; }
                              ^
test.cpp:46:24: note: declared here
         const unsigned number2;

这似乎应该有效,因为B和C都嵌套在A中,并且应该可以访问来自A的数据成员。为什么会这样?有没有办法可行地解决这个问题?

0 个答案:

没有答案