Circular Dependencies / Incomplete Types

后端 未结 3 1089
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 19:19

In C++, I have a problem with circular dependencies / incomplete types. The situation is as follows:

Stuffcollection.h

#include \"Spritesheet.h\";
cl         


        
3条回答
  •  温柔的废话
    2020-12-11 19:56

    Use this form for your nested includes:

    Stuffcollection.h

    #ifndef STUFFCOLLECTION_H_GUARD
    #define STUFFCOLLECTION_H_GUARD
    class Spritesheet;
    class Stuffcollection {
      public:
      void myfunc (Spritesheet *spritesheet);
      void myfuncTwo ();
    };
    #endif
    

    Stuffcollection.cpp

    #include "Stuffcollection.h"
    #include "Spritesheet.h"
    
    void Stuffcollection::myfunc(Spritesheet *spritesheet) {
      unsigned int myvar = 5 * spritesheet->spritevar;
    }
    
    void Stuffcollection::myfuncTwo() {
      //
    }
    

    Spritesheet.h

    #ifndef SPRITESHEET_H_GUARD
    #define SPRITESHEET_H_GUARD
    class Spritesheet {
      public:
      void init();
    };
    #endif
    

    Spritesheet.cpp

    #include "Stuffcollection.h"
    #include "Spritesheet.h"
    
    void Spritesheet::init() {
      Stuffcollection stuffme;
      myvar = stuffme.myfuncTwo();
    }
    

    General rules I follow:

    • Don't include an include from an include, dude. Prefer forward declarations if possible.
      • Exception: include system includes anywhere you want
    • Have CPP include everything it needs, not relying upon H recursively including it files.
    • Always use include guards.
    • Never use pragma

提交回复
热议问题