Nested Class member function can't access function of enclosing class. Why?

后端 未结 4 1674
不知归路
不知归路 2020-12-09 17:02

Please see the example code below:

class A
{
private:
    class B
    {
    public:
        foobar();
    };
public:
    foo();
    bar();
};
4条回答
  •  [愿得一人]
    2020-12-09 17:27

    Basically what Georg Fritzsche said

    #include 
    #include 
    using namespace std;
    
    class A
    {
    private:
        class B
        {
         A& parent_;
         public:
            //B();  //uncommenting gives error
            ~B();
            B(A& parent) : parent_(parent) {}
    
            void foobar() 
            { 
             parent_.foo();  
             cout << "A::B::foo()" <

    If you uncomment the default B constructor you would get an error

提交回复
热议问题