c++ - 多重包含错误,找不到解决方案

标签 c++ file redefinition inclusion

我最近一直在为多个文件包含 错误而苦恼。 我正在开发一款太空街机游戏,并将我的类/对象分成不同的 .cpp 文件并确保一切正常,我构建了以下头文件:

#ifndef SPACEGAME_H_INCLUDED
#define SPACEGAME_H_INCLUDED
//Some Main constants
#define PI 3.14159265


//Standard includes
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;

//SDL headers
#include "SDL.h"
#include "SDL_opengl.h"
#include "SDL_mixer.h"
#include "SDL_image.h"

//Classes and project files
#include "Player.cpp"
#include "planet.cpp"
#include "Destructable.cpp"
#include "PowerUp.cpp"
#include "PowerUp_Speed.cpp"

#endif // SPACEGAME_H_INCLUDED

在我的每个文件的顶部,我(仅)包含了这个包含所有 .cpp 文件和标准包含的头文件。

但是,我有一个 Player/Ship 类,它给了我“重新定义 Ship 类”类型的错误。我最终通过在类定义文件中包含预处理器 #ifndef 和 #define 命令找到了解决方法:

#ifndef PLAYER_H
#define PLAYER_H
/** Player class that controls the flying object used for the space game */
#include "SpaceGame.h"


struct Bullet
{
  float x, y;
  float velX, velY;
  bool isAlive;
};

class Ship
{
    Ship(float sX,float sY, int w, int h, float velocity, int cw, int ch)
    {
        up = false; down = false; left = false; right = false;
        angle = 0;
....
#endif

通过这种解决方法,我丢失了“类/结构重新定义”错误,但它在需要 Ship 类的类文件 PowerUp_Speed 中给了我奇怪的错误:

#include "SpaceGame.h"

class PowerUp_Speed : public PowerUp
{

    public:
        PowerUp_Speed()
        {
            texture = loadTexture("sprites/Planet1.png");
        }

        void boostPlayer(Ship &ship)
        {
            ship.vel += 0.2f;
        }
};

我一直收到以下错误:“无效使用不完整类型‘struct Ship’”和 ''struct ship'的前向声明'

我相信这些错误的根源仍然是我对多个文件包含错误的困扰。 我描述了我为减少错误数量而采取的每一步,但到目前为止都没有 我在 Google 上找到的帖子对我有帮助,所以我礼貌地询问你们是否有人可以帮助我找到问题的根源并解决问题。

最佳答案

通常,您不包括 cpp 文件。
您只需要包含头文件!

当您包含 cpp 文件时,您最终会破坏 One Definition Rule(ODR) .
通常,您的头文件 (.h) 将定义类/结构等,您的源文件 (.cpp) 将定义成员函数等。
根据 ODR,您只能为每个变量/函数等定义,在多个文件中包含相同的 cpp 文件会创建多个定义,因此会破坏 ODR。

How should you go about this?

请注意,为了能够创建对象或调用成员函数等,您需要做的就是在需要创建对象等的源文件中包含定义该类的头文件。您不需要包含任何地方的源文件。

What about Forward Declarations?

总是首选使用前向声明类或结构而不是包含头文件,这样做具有显着的优势,例如:

  • 减少编译时间
  • 没有全局命名空间的污染。
  • 没有预处理器名称的潜在冲突。
  • 二进制大小没有增加(在某些情况下但并非总是如此)

但是,一旦您转发声明了一个类型,您就只能对其执行有限的操作,因为编译器将其视为不完整类型。所以你应该 try to Forward declarations always but you can't do so always .

关于c++ - 多重包含错误,找不到解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11071074/

相关文章:

c++ - 复制构造函数和组合

javascript - 从使用 $http 从服务器下载的原始文件创建 Blob 对象。

python - 如何将文件转换为字典?

C++类重定义错误求助

gcc - 为什么 GCC 4.3 出现 "Redefinition of typedef"错误而不是 GCC 4.6?

c++ - 一个类中的成员变量数量不定? C++

c++ - 如何创建 C++ Boost 无向图并以深度优先搜索 (DFS) 顺序遍历它?

c++ - 在 C 和 C++ 中打印文件的十六进制数

java - 如何使用 AES 在 Java 中加密文件

C++重新定义