從父

2016-04-25 15 views
0

內使用變量我有類此結構:從父

class A { 
    class B; 
    class C; 
    int updates = 0; // invalid use of non-static data member 'A::updates' 
    C* example; 
    class B { 
    public: 
    // ... 
    void up_plus() { 
     updates++; // problem here is too 
    } 
    // And some other methods....... 
    }; 
    class C : public B { 
    public: 
    int size; 
    // ... 
    void sizeup() { 
     example->size++; // invalid use of non-static data member 'A::header' 
    } 
    // And some other methods.... 
    }; 
}; 

我的問題是,我怎麼能解決這個結構呢?在Java中這將工作,但這裏有一個問題。

+0

難道你不想讓B繼承A嗎?或者更新成爲A的靜態成員? – steiner

+3

http://stackoverflow.com/questions/9590265/invalid-use-of-non-static-data-member – tty6

回答

1

語法;

class A { 
    int updates = 0; // allowed in C++11 and above 
// ... 

允許編譯C++ 11標準及以上版本。假設您使用的是clang或g ++,請將-std=c++11-std=c++14添加到命令行。

其次,嵌套類不能立即訪問外部類的實例。他們仍然需要用指針或對「父」的引用來構建。鑑於BC的繼承關係,以下內容可能適合您;

class B { 
    protected: 
    A* parent_; 
    public: 
    B(A* parent) : parent_(parent) {} 
    void up_plus() { 
     parent_->updates++; // addition of parent_ 
    } 
    }; 
    class C : public B { 
    public: 
    int size; 
    void sizeup() { 
     parent_->example->size++; // addition of parent_ 
    } 
    }; 

Working sample here