invalid use of non-static data member

前端 未结 4 1979
暖寄归人
暖寄归人 2021-02-01 14:06

For a code like this:

class foo {
  protected:
    int a;
  public:
    class bar {
      public:
        int getA() {return a;}   // ERROR
    };
    foo()
             


        
4条回答
  •  日久生厌
    2021-02-01 14:32

    In C++, nested classes are not connected to any instance of the outer class. If you want bar to access non-static members of foo, then bar needs to have access to an instance of foo. Maybe something like:

    class bar {
      public:
        int getA(foo & f ) {return foo.a;}
    };
    

    Or maybe

    class bar {
      private:
        foo & f;
    
      public:
        bar(foo & g)
        : f(g)
        {
        }
    
        int getA() { return f.a; }
    };
    

    In any case, you need to explicitly make sure you have access to an instance of foo.

提交回复
热议问题