How to use member of a class in a local class in a method?

帅比萌擦擦* 提交于 2021-01-29 12:30:05

问题


I have a class like this:

class A
{
protected:

 int t = 10;

public:

 void f()
 {
  struct B
  {
   void g()
   {
    print(t); //using t
   }
  };
  B b;
  b.g();
 }
};
ERROR: a nonstatic member reference must be relative to a specific object

I see, members of class A is not visible in struct B (which is inside class A method). But how I may capture they, or make friends A and B? (If it's possible)


回答1:


Defining B inside a method of A does not make instances of A contain a B.

No matter where you define a class, you need an instance to call a non-static method. Making them friends would also not suffice, because you still need an A instance, that you need to pass to B somehow:

class A {
protected:
    int t = 10;
public:
    void f() {
        struct B {
            void g(A& a) {
                int x = a.t;
            }
        };
        B b;
        b.g(*this);
    }
};



回答2:


You need to pass A object (this here) to g method to be able to access A's data. E.g. via parameter:

 void f()
 {
  struct B
  {
   void g(const A& a)
   {
    printf("%d", a.t); //using t
   }
  };
  B b;
  b.g(*this);
 }



回答3:


An instance of the local class B does not hold any aspect of an object of the class A. In order to access member variables of A in B::g(), you'll have to pass a pointer/referece to an instance of A to B::g().

class A
{
   protected:

      int t = 10;

   public:

      void f()
      {
         struct B
         {
            void g(A* a)
            {
               print(a->t);
            }
         };
         B b;
         b.g(this);
      }
};


来源:https://stackoverflow.com/questions/58561649/how-to-use-member-of-a-class-in-a-local-class-in-a-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!