c++ “Incomplete type not allowed” error accessing class reference information (Circular dependency with forward declaration)

后端 未结 3 567
南方客
南方客 2020-12-28 11:55

Had some issues in my code recently surrounding what I now know of as a Circular dependency. In short there are two classes, Player and Ball, which both need to use informat

相关标签:
3条回答
  • 2020-12-28 12:36

    Here is what I had and what caused my "incomplete type error":

    #include "X.h" // another already declared class
    class Big {...} // full declaration of class A
    
    class Small : Big {
        Small() {}
        Small(X); // line 6
    }
    //.... all other stuff
    

    What I did in the file "Big.cpp", where I declared the A2's constructor with X as a parameter is..

    Big.cpp

    Small::Big(X my_x) { // line 9 <--- LOOK at this !
    }
    

    I wrote "Small::Big" instead of "Small::Small", what a dumb mistake.. I received the error "incomplete type is now allowed" for the class X all the time (in lines 6 and 9), which made a total confusion..

    Anyways, that is where a mistake can happen, and the main reason is that I was tired when I wrote it and I needed 2 hours of exploring and rewriting the code to reveal it.

    0 讨论(0)
  • 2020-12-28 12:43

    Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

    Player.cpp:

    #include "Player.h"
    #include "Ball.h"
    
    void Player::doSomething(Ball& ball) {
        ball.ballPosX += 10;                   // incomplete type error occurs here.
    }
    
    0 讨论(0)
  • 2020-12-28 12:54

    If you will place your definitions in this order then the code will be compiled

    class Ball;
    
    class Player {
    public:
        void doSomething(Ball& ball);
    private:
    };
    
    class Ball {
    public:
        Player& PlayerB;
        float ballPosX = 800;
    private:
    
    };
    
    void Player::doSomething(Ball& ball) {
        ball.ballPosX += 10;                   // incomplete type error occurs here.
    }
    
    int main()
    {
    }
    

    The definition of function doSomething requires the complete definition of class Ball because it access its data member.

    In your code example module Player.cpp has no access to the definition of class Ball so the compiler issues an error.

    0 讨论(0)
提交回复
热议问题