error: member access into incomplete type : forward declaration of

前端 未结 2 653
清歌不尽
清歌不尽 2020-12-03 02:43

I have two classes in the same .cpp file:

// forward
class B;

class A {       
   void doSomething(B * b) {
      b->add();
   }
};

class B {
   void a         


        
相关标签:
2条回答
  • 2020-12-03 03:11

    Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

    class B;
    
    class A
    {
        void doSomething(B * b);
    };
    
    class B
    {
    public:
        void add() {}
    };
    
    void A::doSomething(B * b)
    {
        b->add();
    }
    
    0 讨论(0)
  • 2020-12-03 03:11

    You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

    Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

    class B;
    
    class A
    {
        B* b;
    
        void doSomething();
    };
    
    class B
    {
        A* a;
    
        void add() {}
    };
    
    void A::doSomething()
    {
        b->add();
    }
    
    0 讨论(0)
提交回复
热议问题