Error 2061 - Class Becomes “Undefined” When I Include A Header

后端 未结 1 2002
刺人心
刺人心 2021-01-16 19:37

This is very strange and I can\'t get my head around what is causing it.... So I have two classes, Player and Enemy and a utility static class CollisionMgr.

I have a

1条回答
  •  走了就别回头了
    2021-01-16 20:19

    This is a case of a circular dependency. You will need to properly forward declare Player and Enemy and you will not be able to use their definitions in the opposite header file. You can use them in the implementation file. Here's an example:

    Player.h

    class Player
    {
       // needs to know about Enemy
       void f(const Enemy& b);
    };
    

    Enemy.h

    class Enemy
    {
       // needs to know about Player 
       void f(const Player& a);
    };
    

    Including the header file in both locations will cause an error (like you are seeing):

    Player.h

    // This isn't going to work...
    #include "Enemy.h"
    class Player
    {
       // needs to know about Enemy
       void f(const Enemy& b);
    };
    

    Enemy.h

    // This isn't going to work...
    #include "Player.h"
    
    class Enemy
    {
       // needs to know about Player 
       void f(const Player& a);
    };
    

    What is needed here is a "forward declaration" for Player and Enemy where appropriate, like this:

    Player.h

    // forward declaration:
    class Enemy;
    
    class Player
    {
       // needs to know about Enemy
       void f(const Enemy& b);
    };
    

    Enemy.h

    // forward declaration
    class Player;
    
    class Enemy
    {
       // needs to know about Player 
       void f(const Player& a);
    };
    

    Then in the implementation files you can #include the appropriate headers to actually get the definitions of the objects in your compilation unit.

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