定义为:Class.h
#ifndef CLASS_H_
#define CLASS_H_
#include "Class2.h"
#include <iostream>
struct Struct1{
};
struct Struct2{
};
class Class1 {
};
#endif
然后是另一个头文件,我在这里使用它:
#ifndef CLASS2_H_
#define CLASS2_H_
#include "Class.h"
class Class2 {
public:
Class2( Struct1* theStruct, Struct2* theStruct2); //Can't find struct definitions
private:
};
#endif
它们位于同一目录中。它没有看到那些结构定义!他们看起来在全球范围内。有人可以向我解释为什么Class2看不到它们吗?编译器并没有抱怨没有找到Class的头,所以不能这样。
答案 0 :(得分:4)
以下是对完整代码的猜测。请发布,然后我们可以帮助您更好。
如果你的完整的代码看起来如下,那么你应该改变它
#ifndef CLASS_H_
#define CLASS_H_
#include <iostream>
#include "Class2.h"
struct Struct1{
};
struct Struct2{
};
class Class1 {
};
#endif
由于已经定义了CLASS_H_
宏,因此在Class2.h
中,其他标题将不再包含在其他标题中,然后在那时Struct1
和Struct2
还不知道。尽可能使用前向声明来修复它。例如,在Class2.h
:
#ifndef CLASS2_H_
#define CLASS2_H_
// no need for that file
// #include "Class.h"
// forward-declarations suffice
struct Struct1;
struct Struct2;
class Class2 {
public:
Class2( Struct1 theStruct, Struct2 theStruct2);
private:
};
#endif
如果另一个标题也不需要Class2
的定义,那么也使用前向声明。不需要定义(即声明就足够了)
如果您想要访问成员,想要获取sizeof
或想要定义参数类型为Class2
,Struct1
等按值的函数,则需要它。