C++ #include guards

后端 未结 8 838
鱼传尺愫
鱼传尺愫 2020-11-22 13:24

SOLVED

What really helped me was that I could #include headers in the .cpp file with out causing the redefined error.


I\'m new to C++ but I have some p

8条回答
  •  無奈伤痛
    2020-11-22 13:45

    Firstly you need include guards on gameobject too, but that's not the real problem here

    If something else includes physics.h first, physics.h includes gameobject.h, you get something like this:

    class GameObject {
    ...
    };
    
    #include physics.h
    
    class Physics {
    ...
    };
    

    and the #include physics.h gets discarded because of the include guards, and you end up with a declaration of GameObject before the declaration of Physics.

    But that's a problem if you want GameObject to have a pointer to a Physics, because for htat physics would have to be declared first.

    To resolve the cycle, you can forward-declare a class instead, but only if you are just using it as a pointer or a reference in the declaration following, i.e.:

    #ifndef PHYSICS_H
    #define PHYSICS_H
    
    //  no need for this now #include "GameObject.h"
    
    #include 
    
    class GameObject;
    
    class Physics
    {
    private:
        list objects;
        list::iterator i;
    public:
        void ApplyPhysics(GameObject*);
        Vector2X CheckCollisions(Vector2X, GameObject*);
    };
    
    #endif // PHYSICS_H
    

提交回复
热议问题