所以我正在制作一个我想要使用资产管理器的图形应用程序(游戏)。对于本课程,我决定使用Singleton Design。所以在我的main.cpp中我会加载像......
ASSET_MANAGER.LoadImage("res/graphics/background.png", "background");
以上是上述行中使用的宏/方法的含义。这是一种代码混搭,我必须让事情变得更简单,而不是在这里粘贴几百行代码。
assetmanager.h
#define ASSET_MANAGER AssetManager::GetAssetManager()
#define DEBUG
class AssetManager {
public:
static AssetManager &GetAssetManager();
//-----------------------------------------------------------------------------
// Purpose: Load a new image for the game to use. This function will store an
// instance of the asset in memory (in a hash map corresponding with
// the data type provided.
//
// param file: The location on disk of the asset
// param key: The string you use to receive this asset (defaults to the path str)
//-----------------------------------------------------------------------------
bool LoadImage(const char *file, const char *key = "");
//-----------------------------------------------------------------------------
// Purpose: Returns the image
//
// param key: The string used to store the asset in memory
//-----------------------------------------------------------------------------
ALLEGRO_BITMAP *GetImage(const char *key);
//-----------------------------------------------------------------------------
// Purpose: Destroys an asset that is presumably no longer needed by the game.
// This function is good for performance so that you don't use more
// RAM than you need to.
//
// param key: The string you use to receive this asset (defaults to the path str)
//-----------------------------------------------------------------------------
void DiscardImage(const char *key);
private:
AssetManager();
~AssetManager();
std::map<const char *, std::shared_ptr<ALLEGRO_BITMAP>> _ImageMap;
}
assetmanager.cpp
AssetManager &AssetManager::GetAssetManager() {
static AssetManager instance;
return instance;
}
bool AssetManager::LoadImage(const char *file, const char *key) {
key = key == "" ? file : key;
std::shared_ptr<ALLEGRO_BITMAP> x(al_load_bitmap(file), al_destroy_bitmap);
if (!x) {
fprintf(stderr, "Failed to load %s\n", file);
return false;
}
#ifdef DEBUG
printf("DEBUG: Loaded %s\n", key); //debug
#endif // DEBUG
_ImageMap.insert(std::pair<const char *, std::shared_ptr<ALLEGRO_BITMAP>>(key, x));
return true;
}
ALLEGRO_BITMAP *AssetManager::GetImage(const char *key) {
return _ImageMap.find(key) != _ImageMap.end() ? _ImageMap.at(key).get() : nullptr;
}
void AssetManager::DiscardImage(const char *key) {
_ImageMap.erase(key);
#ifdef DEBUG
printf("DEBUG: Discarded %s\n", key); //debug
#endif // DEBUG
}
这个类只适用于我初始化资产管理器的类,而我期望它可以在我调用ASSET_MANAGER的任何地方工作。它编译得很好,当我尝试在不同的类中使用管理器并将其传递给allegro函数时它只会崩溃,因为它返回的是null而不是正确的allegro数据类型。我对此不了解什么?
答案 0 :(得分:0)
地图中的Char *存储位置,而不是使程序认为它为空的数据。