【问题标题】:Declaring variable from third party library in header file在头文件中从第三方库声明变量
【发布时间】:2020-11-21 23:16:55
【问题描述】:

我有一个游戏类如下:

// 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 中的所有内容,我想避免这些内容。理想情况下,我只想在源文件 (.cpp) 中包含 game_engine

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

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

【问题讨论】:

  • 你可能正在寻找疙瘩成语。
  • 进一步研究的术语是“前向声明”。在头文件中class Game {之前添加这一行:class Texture;
  • 为什么不希望头文件包含在其他源文件中?
  • @IgorTandetnik - 谢谢,我试过了,但我收到一个错误 - Use of undefined type TextureTexture 是第三方库中的 struct,这会有所不同吗?
  • 在哪一行代码中出现“使用未定义类型纹理”错误? This code compiles;有问题的话,一定是代码中没有显示出来。

标签: c++


【解决方案1】:

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

源文件如下:

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

如果我想使用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 2021-12-05
    • 2010-11-12
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多