前瞻性声明循环依赖 [英] Forward declaration & circular dependency

查看:231
本文介绍了前瞻性声明循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,Entity和Level。两者都需要访问彼此的方法。因此,使用#include,出现循环依赖的问题。因此为了避免这种情况,我试图在Entity.h中转发declare Level:

  class Level {}; 

但是,由于Entity需要访问Level中的方法,所以它不能访问这些方法,知道他们存在。有没有办法解决这个问题,而不重新声明Entity中的大多数级别?

解决方案

  class Level; 

注意缺少花括号。这告诉编译器有一个名为 Level 的类,但是没有内容。然后你可以自由地使用指针( Level * )和引用( Level& p>

请注意,由于编译器需要知道类的大小来创建变量,因此不能直接实例化 Level

  class Level; 

class Entity
{
级别&level; // legal
级别; // illegal
};

为了能够使用 Level code> Entity 的方法,你最好在单独的<$>中定义 Level c $ c> .cpp 文件,并且只在标题中声明。从定义中分离声明是一个C ++最佳实践。

  // entity.h 

class Level;

class Entity
{
void changeLevel(Level&);
};


// entity.cpp

#includelevel.h
#includeentity.h

void Entity :: changeLevel(level& level)
{
level.loadEntity(* this);
}


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 { };

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;

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.

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
};

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);
}

这篇关于前瞻性声明循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆