C++ circular include

后端 未结 4 1197
野的像风
野的像风 2020-12-06 03:26

I can\'t solve this circular dependency problem; always getting this error: \"invalid use of incomplete type struct GemsGame\" I don\'t know why the compiler doesn\'t know t

相关标签:
4条回答
  • 2020-12-06 03:34

    Two ways out:

    1. Keep the dependent classes in the same H-file
    2. Turn dependency into abstract interfaces: GemElement implementing IGemElement and expecting for IGemsGame, and GemsGame implementing IGemsGame and containing a vector of IGemElement pointers.
    0 讨论(0)
  • 2020-12-06 03:39

    If you deference the pointer and the function is inline you will need the full type. If you create a cpp file for the implementation you can avoid the circular dependecy (since neither of the class will need to include each others .h in their headers)

    Something like this:

    your header:

    #ifndef GEMELEMENT_H_INCLUDED
    #define GEMELEMENT_H_INCLUDED
    
    class GemsGame;
    
    class GemElement {
        private:
            GemsGame* _gemsGame;
    
        public:
            GemElement();
    };
    
    
    #endif // GEMELEMENT_H_INCLUDED
    

    your cpp:

    #include "GenGame.h"
    GenElement::GenElement()
    {
       _gemsGame = application.getCurrentGame();
       _gemsGame->getGemsVector();
    }
    
    0 讨论(0)
  • 2020-12-06 03:40

    Look at the top answer of this topic: When can I use a forward declaration?

    He really explains everything you need to know about forward declarations and what you can and cannot do with classes that you forward declare.

    It looks like you are using a forward declaration of a class and then trying to declare it as a member of a different class. This fails because using a forward declaration makes it an incomplete type.

    0 讨论(0)
  • 2020-12-06 03:52

    Remove the #include directives, you already have the classes forward declared.

    If your class A needs, in its definition, to know something about the particulars of class B, then you need to include class B's header. If class A only needs to know that class B exists, such as when class A only holds a pointer to class B instances, then it's enough to forward-declare, and in that case an #include is not needed.

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