C++ includes - Cross referencing files
In C++, I have A.h and B.h. I need to include A.h in B.h, then I needed to use an object from B inside A.cpp. So I included B.h in A.h so it refused. I tried to use these lines in .H files
#ifndef A_H
#define A_H
...my code
#endif
I had the same refused. so I tried in A.h file to put
class B;
as a defined class. so it took it as another class not th开发者_运维问答e same B class which i want. what i have to do?
See this FAQ
You cannot include A.h in B.h and also include B.h in A.h - it is a circular dependency.
If a structure or function in A need to reference a pointer to a structure in B (and vice-versa) you could just declare the structures without defining them.
In A.h:
#ifndef __A_H__
#define __A_H__
struct DefinedInB;
struct DefinedInA
{
DefinedInB* aB;
};
void func1(DefinedInA* a, DefinedInB* b);
#endif __A_H__
In B.h:
#ifndef __B_H__
#define __B_H__
struct DefinedInA;
struct DefinedInB
{
DefinedInA* anA;
};
void func2(DefinedInA* a, DefinedInB* b);
#endif __B_H__
You can do this only with pointers, again to avoid the circular dependency.
In general, it is better to avoid circular references, but if you need them in your design, and your dependencies are as follows:
a.h <-- b.h <-- a.cpp (where x <-- y represents "y" depends on "x")
Just type that in:
// A.h
#ifndef A_HEADER
#define A_HEADER
...
#endif
// B.h
#ifndef B_HEADER
#define B_HEADER
#include "A.h"
...
#endif
// A.cpp
#include "A.h"
#include "B.h"
// use contents from both A.h and B.h
精彩评论