由于循环依赖,我在另一个对象中声明外部对象时遇到问题。请考虑以下事项:
LevelEditor 对象包含一个模块数组(所有模块都是 editor_module 的子模块):
#include "../Objects/editor_module.h"
#include "Modules/collisionGrid_module.h"
#include "Modules/HUD_module.h"
#include "Modules/IO_module.h"
#include "Modules/ledge_module.h"
#include "Modules/segment_module.h"
namespace g_editor
{
class LevelEditor
{
但是模块需要返回到编辑器才能使用它的功能:
#pragma once
#include "../LevelEditor/LevelEditor.h"
extern g_editor::LevelEditor g_levelEditor;
namespace g_editor
{
class editor_module
{
在编译时,存在循环依赖问题。是否有我忽略的设计注意事项?
最佳答案
如果模块只需要类的引用,那么它们不需要完整的类定义,只需要一个前向声明:
namespace g_editor {class LevelEditor;}
任何需要完整定义(例如访问它的成员)的代码,例如模块的成员函数中的代码,都必须放在源文件中,其中包含头文件。但是模块的类定义本身不需要它。
关于C++:外部对象循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057706/