未定义的基础 class,但包括现在

Undefined base class, though includes present

Forehand 我想提一下我对 C++ 编程还很陌生,我使用 Ogre3D 作为框架(出于学校项目的原因)。 我有一个 class Player 继承自 GameObject class。尝试构建项目时遇到以下错误:

Error C2504 'GameObject' : base class undefined - player.h (9)

这意味着游戏对象 class 在玩家 class' header 文件中未定义。然而,我实际上已经将 GameObject header 文件包含在播放器的文件中(请参见下面的代码)。我知道循环包括代码中正在发生。但是,如果我遗漏了这些包括,我会得到一个完整的不同错误列表,我不确定它们是如何或为什么发生的:

我已经被这个问题难住了几天了,到目前为止还没有在互联网上找到任何解决方案(我主要参考的CPlusPlus文章:http://www.cplusplus.com/forum/articles/10627/)。

下面列出的 header 个文件的源文件只包含它们各自的 header 个文件。

Player.h

#pragma once

#ifndef __Player_h_
#define __Player_h_

#include "GameObject.h"

class Player : public GameObject {
    // ... Player class interface
};
#endif

GameObject.h

#pragma once

#ifndef __GameObject_h_
#define __GameObject_h_

#include "GameManager.h"

// Forward declarations
class GameManager;

class GameObject {
// ... GameObject class interface
};
#endinf

GameObject header 包括 GameManager 可以看出。

GameManager.h

#pragma once

// Include guard
#ifndef __GameManager_h_
#define __GameManager_h_

// Includes from project
#include "Main.h"
#include "Constants.h"
#include "GameObject.h" // mentioned circular includes
#include "Player.h" // "

// Includes from system libraries
#include <vector>

// Forward declarations
class GameObject;

class GameManager {
// ... GameManager interface
};
#endif

最重要的是 class 主文件,header 文件如下所示:

Main.h

// Include guard
#ifndef __Main_h_
#define __Main_h_

// Includes from Ogre framework
#include "Ogre.h"
using namespace Ogre;

// Includes from projet headers 
#include "BaseApplication.h"
#include "GameManager.h"

// forward declarations
class GameManager;

class Main : public BaseApplication
{
// ... Main interface
};
#endif

根据我对这个主题和其他有同样错误的人所做的所有阅读,我认为我能够弄清楚,但仍然无济于事。我希望有人能花时间在这里帮助我并指出任何错误的代码或约定。

我认为解决该问题的最简单方法是更改​​您的模型以包含 header 文件。如果 B.h 定义了一个在 A.h 中(直接)使用的符号,文件 A.h 应该只包含 B.h。将 using 子句放在 header 文件中通常也是一个坏主意 - 让客户端代码的程序员做出决定。除非绝对必要,否则放弃 classes 的前向声明;在#include "GameManager.h" 之后不需要 class GameManager。我怀疑代码还有其他问题,但是 classes 的前向声明隐藏了这个问题。如果更改包含不能解决问题,请从包含 "simplest" header(不依赖于任何其他文件的文件)的单个 .cpp 文件开始,然后构建完整的包括。