问题描述
我有两个类,Entity 和 Level.两者都需要访问彼此的方法.因此,使用#include,就会出现循环依赖的问题.因此为避免这种情况,我尝试在 Entity.h 中转发声明 Level:
I've got two classes, Entity and Level. Both need to access methods of one another. Therefore, using #include, the issue of circular dependencies arises. Therefore to avoid this, I attempted to forward declare Level in Entity.h:
class Level { };
但是,由于实体需要访问 Level 中的方法,它不能访问这些方法,因为它不知道它们存在.有没有办法在不重新声明实体中的大部分级别的情况下解决这个问题?
However, as Entity needs access to methods in Level, it cannot access such methods, since it does not know they exist. Is there a way to resolve this without re-declaring the majority of Level in Entity?
推荐答案
正确的前向声明很简单:
A proper forward declaration is simply:
class Level;
请注意缺少花括号.这告诉编译器有一个名为 Level
的类,但没有关于它的内容.然后,您可以自由地使用指向此未定义类的指针(Level *
)和引用(Level &
).
Note the lack of curly braces. This tells the compiler that there's a class named Level
, but nothing about the contents of it. You can then use pointers (Level *
) and references (Level &
) to this undefined class freely.
请注意,您不能直接实例化 Level
,因为编译器需要知道类的大小才能创建变量.
Note that you cannot directly instantiate Level
since the compiler needs to know the class's size to create variables.
class Level;
class Entity
{
Level &level; // legal
Level level; // illegal
};
为了能够在 Entity
的方法中使用 Level
,您最好define Level
的方法在单独的 .cpp
文件中,并且仅在标题中 declare 它们.将声明与定义分开是 C++ 的最佳实践.
To be able to use Level
in Entity
's methods, you should ideally define Level
's methods in a separate .cpp
file and only declare them in the header. Separating declarations from definitions is a C++ best practice.
// entity.h
class Level;
class Entity
{
void changeLevel(Level &);
};
// entity.cpp
#include "level.h"
#include "entity.h"
void Entity::changeLevel(Level &level)
{
level.loadEntity(*this);
}
这篇关于远期申报循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!