#include和可能的循环参考 [英] #include and possible cyclical reference

查看:69
本文介绍了#include和可能的循环参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我最近的错误开始让我感到非常糟糕,我环顾了互联网,我想到的最好的解决方案是出现周期性的 #include 错误,但是我我不确定是什么原因造成的.我的包含结构如下所示:

So my latest error is starting to bug me really bad and I've looked around the internet and the best solution I have come up with is that I have a cyclical #include error, but I'm not sure what is exactly causing that. My include structure looks like the following:

Player.h -includes-> Pawn.h -includes-> Piece.h -includes-> Player.h

我的意思是,对我来说,这似乎是一个周期性的包含问题,但我不知道该如何克服.为了使事情复杂化,类 Pawn 扩展了 Piece ,而 Piece boost :: weak_ptr 返回到播放器.我包含这个内容的原因是因为 Player 具有 Pawn s(和其他 Piece s)的 vector 但是 Pawn 也需要调用某些 Player 的方法,因此我为基类Piece赋予了 Player weak_ptr 代码>.

I mean, it seems obvious to me that this is a cyclical include problem, but I don't know how to overcome this. To complicate things, class Pawn extends Piece, and Piece has a boost::weak_ptr back to Player. The reason my includes looks like this is because Player has a vector of Pawns (and other Pieces) but Pawn also needs to call some of Player's methods, so I gave the base class Piece a weak_ptr to Player for that.

怎样才能更好地进行设计,以使我没有周期性的包含?

What is a way that I can design this better so that I don't have a cyclical include?

推荐答案

您可以通过使用前向声明来解决此问题.实际上,在大多数情况下,您应该希望它们包括标头.

You can work around this by using forward declarations; in fact, you should prefer them to including headers in most cases.

当标头不需要了解另一个类的实现详细信息时,可以为它使用前向声明,而不是包括整个类定义.这基本上告诉编译器有一个具有该名称的类",但没有其他内容.

When a header doesn't need to know about any of the implementation details of another class, you can use a forward declaration for it, instead of including the entire class definition. This basically tells the compiler 'There's a class with this name,' but nothing else.

// This is a forward declaration. It tells the compiler that there is a 
// class named Player, but it doesn't know the size of Player or what functions
// it has.
class Player; 

struct Piece {
   // This is just a pointer to player. It doesn't need to know any details about
   // Player, it just needs to know that Player is a valid type.
   boost::weak_ptr<Player> player;
};

作为一般规则,如果文件仅绕过某种类型的指针或引用,则应向前声明该类型.但是,如果尝试实际使用该类型的对象,则将导致编译器错误.在这种情况下,您需要包括适当的标题.

As a general rule, if a file only passes around a pointer or reference to a certain type, that type should be forward declared. However, if it tries to actually use an object of that type, it will result in a compiler error. In this case, you need to include the appropriate header.

在大多数情况下,您将希望在源文件中包括任何向前声明的类的标头,因此您实际上可以使用所指向的对象.

In most cases, you'll want to include the headers for any forward declared classes in the source file, so you can actually use the objects that are being pointed to.

这篇关于#include和可能的循环参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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