首页 > 解决方案 > 在头文件中从第三方库声明变量

问题描述

我有一个游戏类如下:

// game.h
class Game {
 public:
  void Run();
  void CleanUp();
}

我想创建一个在此处声明但在构造时启动的纹理指针。此指针指向存在于第三方头文件中的类型:

private:
 std::unique_ptr<Texture> sprite_sheet; // Texture is in game_engine.h which is third party.

问题是,如果我#include "game_engine.h"在此标头中,则包含此标头的每个文件都将包含game_engine我想要避免的所有内容。理想情况下,我只想包含game_engine在源文件 ( .cpp) 中。

是否有标准的设计模式可以帮助我避免这种情况?

一种方法是创建我自己的Texture类,它只公开我想要的相关部分。但这会慢慢变得不成比例,因为我将不得不为所有事情重新做我自己的课程。

标签: c++

解决方案


发布答案,因为还有更多的完整性。这对我有用。

源文件如下:

// game_engine.h - C library.
typedef struct Texture {
  ...
} Texture;

如果我想使用 a unique_ptr,方法如下:

// game.h
// Forward declare the typedef.
// https://stackoverflow.com/q/804894/1287554
typedef struct Texture Texture_;

class Game {
 public:
  void Run();
  void CleanUp();
  
  // Destructor is required for unique_ptr and forward declarations.
  // https://stackoverflow.com/q/13414652/1287554
  ~Game();
 protected:
  std::unique_ptr<Texture_> sprite_sheet;

};


// game.cpp
#include "game.h" // This is first.
#include "game_engine.h"

void Game::Run() {
  sprite_sheet = std::make_unique<Texture_>(LoadTexture(...));
}

// This has to be explicit.
Game::~Game() = default;

推荐阅读