C++ cyclical header dependency
I had a question: Supposed I have a header/source file set and a header set as follows"
BaseCharacter.h and BaseCharacter.cpp and EventTypes.h
BaseCharacter.h makes use of structs and typedefs defined in EventTypes.h, but EventTypes.h has to be aware of the BaseCharacter class defined in BaseCharacter.h. This creates a cyclical dependency and I'm pretty sure that's whats stopping my program from compiling. If I take out EventTypes.h and all the me开发者_运维技巧thods that rely on the stuff in EventTypes.h, my program compiles fine. But if I added EventTypes.h, it, and every file referencing BaseCharacter.h will complain that it can't find the BaseCharacter class.
Is there a way around this dependency or would this not be what's causing my problem?
I'm using MSVC 2010 as my compiler
Forward declaration.
In EventTypes.h, remove the include and add:
class BaseCharacter;
Note that you can only use references and pointers to BaseCharacter
within EventTypes.h, you cannot e.g. have a struct with a BaseCharacter myChar;
member variable.
You should probably have a good look at your design and make sure it makes sense; often cyclical dependencies indicate a sub-optimal design (though it's possible that it's the best solution for your needs).
In any case, you can predeclare the classes upfront in each header file, thus avoiding having circular includes. This is called using forward declarations.
Another good option would be to extract the stuff that both BaseCharacter.h and EventTypes.h depend on into a third header file that the first two include; then you'd only have a one-way dependency of EventTypes.h on BaseCharacter.h.
A third alternative is to simply merge everything into one header file; this may or may not make sense based on your design, but if the inter-dependencies are strong enough, then surely a unified model makes sense?
You want to learn how to forward declare classes and structs.
See here: cyclic dependency between header files
or here: C++ error: 'Line2' has not been declared
Just to add to the answers mentioning forward declaration, there is another alternative which is slightly different, and it is called PIMPL, which stands for Pointer to IMPlementation. It is often used in conjunction with forward declaration, but can be used without. Not only it helps to solve cyclic dependency problems, but can also dramatically speed up build time and reduce code dependency.
Once I had similar problem, solved it with templates. Can't you define the EventTypes and/or BaseCharacter as template?
精彩评论