1

我是游戏开发的菜鸟,我想用 C++ 制作一个简单的平台游戏。问题是当我创建两个类(游戏和图形)时,我不能在 Graphics.h 中包含 Game.h,因为我已经在 Game.h 中包含了 Graphics.h。有谁能够帮我?代码:Game.h:

#pragma once

#include "Graphics.h"

struct Game {
    Game();

    void init();
    void handle();

    bool running;

    Graphics g;
};

图形.h:

#pragma once

#include <SDL.h>

struct Graphics {
    SDL_Surface* screen;

    void init();

    void rect(SDL_Rect rect, Uint32 color);
    void rect(SDL_Rect rect, int r, int g, int b);
    void rect(int x, int y, int w, int h, Uint32 color);
    void rect(int x, int y, int w, int h, int r, int g, int b);

    void render(Game* game);
};
4

2 回答 2

9

您可以在此处使用前向声明:

#ifndef GRAPHICS_H_ // portable include guards
#define GRAPHICS_H_

#include <SDL.h>

class Game; // forward declaration. Exactly the same as struct Game.

struct Graphics 
{
  // as before
};

#endif

因为Graphics不需要定义Game. 您很可能需要Game.hGraphics.

请参阅相关帖子:何时使用前向声明?

于 2013-09-15T07:08:08.377 回答
1

您可以有一个合并两个Game.h和的标题Graphic.h;没有理由每个班级有一个标题。

如果使用GCC(然后用 编译g++ -Wall -g),整个项目只有一个头文件的优点是能够预编译头文件。另请参阅此答案

于 2013-09-15T07:08:19.470 回答