Inclusion problem
I have an inclusion pattern as follows:
/*
* Class1.h
*/
#ifndef CLASS1_H_
#define CLASS1_H_
#include "Class2.h"
namespace Class1_namespace
{
class Class1
{
Class2* Class2_ptr;
void Class1_member()
{
(*Class2_ptr).Class2_method();
}
};
}
#endif /* CLASS1_H_ */
/*
* Class2.h
*/
#ifndef CLASS2_H_
#define CLASS2_H_
#include "Class1.h"
class Class2
{
Class1开发者_C百科_namespace::Class1 Class2_data;
public:
void Class2_method(){};
};
#endif /* CLASS2_H_ */
/*
* main.cpp
*/
#include "Class1.h"
int main()
{
return 0;
}
However, this leads to the error “'Class1_namespace' does not name a type.”
Is this error caused by the ordering of my inclusions?
What are some possible solutions? I'm dubious about forward declarations solving my problem.
Class1 doesn't need to include Class2.
When you have mutual dependency (which you don't -- you could just not include 2 in 1), you can usually solve it by using forward declarations instead of inclusions.
For example, let's say that Class1 looked like this
#include "Class2.h"
namespace Class1_namespace
{
class Class1
{
Class2* class2;
};
}
Where you think you need the include, you could instead do this:
class Class2;
namespace Class1_namespace
{
class Class1
{
Class2* class2;
};
}
to break the mutual inclusion.
In class1.h, try removing the unnecessary and circular #include of class2.h. If a circular dependency is required -- or even if not -- consider using forward declarations.
精彩评论