Circular dependencies in c++
Say I have these two classes:
// a.h
#include "b.h"
开发者_C百科and:
// b.h
include "a.h"
I understand there is a problem over here, but how can I fix it and use a
objects and their methods in b
class and vice versa?
You can use forward declarations, like this:
class B;
class A
{
B* ThisIsValid;
}
class B
{
A SoIsThis;
}
For more information, see this SO question.
As for the preprocessor #include
s, there's likely a better way to organize your code. Without the full story, though, it's hard to say.
To extend on @Borealid 's answer:
To avoid problems with circular includes, using an "include guard"
eg.
#ifndef MYFILE_H /* If this is not defined yet, it must be the first time
we include this file */
#define MYFILE_H // Mark this file as already included
// This only works if the symbol we are defining is unique.
// code goes here
#endif
You can use what is called a "forward declaration".
For a function, this would be something like void myFunction(int);
. For a variable, it might look like extern int myVariable;
. For a class, class MyClass;
. These bodiless statements can be included before the actual code-bearing declarations, and provide the compiler with enough information to produce code making use of the declared types.
To avoid problems with circular includes, using an "include guard" - an #ifdef
at the top of each header file which prevents it being included twice.
The "other" class can only have a reference or pointer to the "first" class.
in file a.h:
#include "b.h"
struct a {
b m_b;
};
in file b.h:
struct a;
struct b {
a* m_a;
};
void using_the_a_instance(b& theb);
in file b.cpp:
#include "b.h"
#include "a.h"
void using_the_a_instance(b& theb)
{
theb.m_a = new a();
}
精彩评论