Forward declaration amp; circular dependency(远期申报循环依赖)
问题描述
我有两个类,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);
}
这篇关于远期申报循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:远期申报循环依赖
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
