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

后端 未结 3 597
南方客
南方客 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: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.

提交回复
热议问题