假设我们有两个类:
// Object.hpp
class Object
{
Handler* h;
Object();
void method();
};
// Object.cpp
Object::Object()
{
h = new Handler();
}
// Handler.hpp
class Handler
{
void update(Object*);
};
// Handler.cpp
void Handler::update(Object* o)
{
o->method();
}
如何链接这四个文件而不出现包含错误?我已经尝试了所有我能想到的和我可以在网上找到的方法。
在两个文件中添加#include
将导致此错误:
Handler.hpp: error: ‘Object’ has not been declared
update(Object*);
^
如果我在处理程序中添加对象的前向声明,我会得到:
Object.hpp: error: ‘Handler’ does not name a type
Handler handler
在 Handler.hpp 中包含 Object 并在 Object.hpp 中向前声明 Handler 会得到以下结果:
Object.hpp: error: field ‘h’ has incomplete type ‘Handler’
Handler handler;
^
同时,在 Object.hpp 中包含 Handler 时,在 Handler.hpp 中向前声明对象会给出以下结果:
Handler.cpp: error: invalid use of incomplete type ‘class Object’
o->method();
^
我似乎无法找出将文件相互包含的方法。该结构基于 Robert Nystrom's Game Programming Patterns 中的解耦组件模式。 。任何帮助表示赞赏。谢谢
最佳答案
您发布的错误似乎不是来自您提供的代码。
问题
Object.hpp: error: ‘Handler’ does not name a type
Handler handler //<-- Declaration of object of type Handler, not pointer
是 handler
被声明为对象,而不是指针。因此,编译器需要知道定义。这就是为什么前向声明(forward declaration)是不够的。如果您在提供的 Object.hpp 中添加 Handler 的前向声明,它应该可以工作:
// Object.hpp
//forward-declaration of Handler
class Handler;
class Object
{
Handler* h;
Object();
void method();
};
// Object.cpp
//include Handler.hpp
#include "Handler.hpp"
Object::Object()
{
h = new Handler();
}
// Handler.hpp
//include Object.hpp
#include "Object.hpp"
class Handler
{
void update(Object*);
};
// Handler.cpp
void Handler::update(Object* o)
{
o->method();
}
编辑以在 Object.cpp 中添加包含内容并根据 @TonyK 的评论删除第一段
关于c++ - 循环文件包含 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60973434/