管理C++ include指令的正确方法

adi*_*ile 2 c++ include

我对C++如何处理包含有点困惑.

我有类似的东西:

typedef struct {
  //struct fields
} Vertex;

#include "GenericObject.h"
Run Code Online (Sandbox Code Playgroud)

现在在GenericObject.h我有:

class GenericObject {
  public:
    Vertex* vertices; 
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,编译器说:

ISO C++禁止声明'Vertex'没有类型

如何让GenericObject.h了解Vertex?

我认为在#include之前定义的任何内容都可以在包含的文件中找到.

最后,你能否给我一些关于如何正确使用#include而不引入太多冗余或循环包含的技巧.

谢谢.

Sky*_*leh 9

两件事,首先你要它只是......

struct Vertex
{
//struct fields
};
Run Code Online (Sandbox Code Playgroud)

这是C++中正确定义的结构.现在您需要在通用对象头中包含Vertex.h或者包含顶点结构的文件,

#include "Vertex.h"
class GenericObject {
public:
   Vertex* vertices; 
};
Run Code Online (Sandbox Code Playgroud)

或者向前声明它......

struct Vertex;
class GenericObject {
  public:
    Vertex* vertices; 
};
Run Code Online (Sandbox Code Playgroud)

不要#include"Vertex.h"中的"GenericObject.h".

  • 不,他/她*不应该*需要在这种情况下转发声明它.再看看OP的代码片段. (3认同)