invalid use of non-static data member

前端 未结 4 1993
暖寄归人
暖寄归人 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:19

    The nested class doesn't know about the outer class, and protected doesn't help. You'll have to pass some actual reference to objects of the nested class type. You could store a foo*, but perhaps a reference to the integer is enough:

    class Outer
    {
        int n;
    
    public:
        class Inner
        {
            int & a;
        public:
            Inner(int & b) : a(b) { }
            int & get() { return a; }
        };
    
        // ...  for example:
    
        Inner inn;
        Outer() : inn(n) { }
    };
    

    Now you can instantiate inner classes like Inner i(n); and call i.get().

提交回复
热议问题