C++ Base class 编译时未定义

C++ Base class undefined while compiling

我在尝试编译时得到 GameObject: base class undefined。我看不出有什么不对。我在 GameObject 和玩家之间有父子关系:

GameObject.h

#pragma once
#include "Game.h"

class GameObject
{
protected:
    int x, y;

    SDL_Texture* objTexture;
    SDL_Rect srcRect{}, destRect{};

public:
    GameObject(const char* textureSheet, int p_x, int p_y);
    ~GameObject();

    void Update();
    void Render();
};

Player.h

#pragma once
#include "GameObject.h"

class Input;

class Player : public GameObject
{
private:
    Input* input{ nullptr };
public:
    Player(Input * p_input);
    ~Player();

    void Update();
};

这是Game.h

#pragma once
#include <SDL.h>
#include <SDL_image.h>
#include "TextureManager.h"
#include "Player.h"
#include "Map.h"
#include "Input.h"

class Player;
class Map;
class Input;

class Game
{
private:
    SDL_Window* window{ nullptr };

    Player* player{ nullptr };
    Input* input{ nullptr };

    Map* map{ nullptr };

    bool isRunning = false;

public:
    Game();
    Game(const char* title, int xPos, int yPos, int width, int height, bool fullscreen);
    ~Game();

    void HandleEvents();
    void Update();
    void Render();
    void clean();
    bool running() { return isRunning; };
    
    static SDL_Renderer* renderer;
};

我看到的大多数讨论都说这是由于一些重复的包含创建了循环依赖,但我没有看到任何问题。这和游戏有关吗class?

如果您向我们提供确切的错误消息并指出行号,将会有所帮助。

我怀疑这是因为您的 GameObject 有一个需要参数的构造函数,但您的 Player class 没有在其构造函数初始化列表中提供这些参数。

但这只是猜测。

新猜想! GameObject.h 中的 #include "Game.h" 是问题所在。

只包含您使用的内容,永远不要创建循环引用,即使您使用 #pragma once该编译指示并不像某些人认为的那样。

而不是 Game.h 包含您需要的 SDL header。

尽可能从 header 文件中删除 header 包含,并使用任何指针的前向声明。仅在您的源文件(.cpp 文件)中包含 header 的具体定义。

您真的想避免包含一个 header 并让它拉入包含 500 个其他包含文件的巨大网络的问题。

您将需要 SDL header 才能使用 SDL_Rect

最简单的方法是转发声明缺少的 class 个原型。

class SDL_Texture;
class SDL_Rect;

正如您在 Player.h

中已经开始的那样

一种更具防御性的方法是始终在每个源文件中包含所有需要的 header。

#include <SDL.h>

或另一个 SDL header.

并且您已经解决了

的循环包含
#pragma once