invalid use of non-static data member

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

    In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA doesn't have any specific instance of foo whose a it can be returning. I'm guessing that what you want is something like:

        class bar {
          private:
            foo * const owner;
          public:
            bar(foo & owner) : owner(&owner) { }
            int getA() {return owner->a;}
        };
    

    But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected member a. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)

提交回复
热议问题