c++ - 在头文件中从第三方库声明变量
问题描述
我有一个游戏类如下:
// 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
类,它只公开我想要的相关部分。但这会慢慢变得不成比例,因为我将不得不为所有事情重新做我自己的课程。
解决方案
发布答案,因为还有更多的完整性。这对我有用。
源文件如下:
// 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;
推荐阅读
- office-ui-fabric - 有没有一种简单的方法来更改嵌套导航组件中的人字形图标?
- javascript - 如何使用 moment 或 js 将 DD-MM-YYYY HH:mm 格式转换为纪元时间?
- swift - 当我第二次注册时,它会迅速从 firebase 中清除实时数据库
- python - Python pandas:使用包含和连接语句从另一个数据帧中过滤
- flutter - Flutter - 从相机拍摄的照片上的拉绳
- c - Richedit 中的文本突出显示和 UNDO
- openlayers - Openlayers 弹出窗口在缩小时不遵循所选功能
- c# - WPF 应用程序不能使用自己的注册表项
- python - Pip install PyAudio 在 Windows 上失败
- c++ - C++ 的高级打印函数