gpt4 book ai didi

c++ - 对象管理——容器还是工厂?

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:50 25 4
gpt4 key购买 nike

我的游戏编程入门类(class)即将结束,我想结合我在类里面学到的技能和我之前的 OOP 经验来创建一个用于制作 2D 游戏的小型库。不过,我目前担心的是,这是管理我的类实例集合的最佳方式。

我正在使用的库 (DarkGDK) 完全由作用于整数的自由函数组成。当使用诸如 dbSprite() 之类的函数创建“对象”时,您会为它指定一个唯一 ID(int 值)以引用它——我猜是某种“地址”。我个人觉得这种方法很糟糕,所以我创建了类来封装每组自由函数,例如 Image、Sprite 和 AnimatedSprite(这两种 Sprite 类型在 DarkGDK 库中是不同的。)

问题是,为了让这些对象工作,我仍然必须将唯一 ID 传递给构造函数,以便针对适当的地址调用 DarkGDK 函数。我试图摆脱通过 ID 一起引用这些东西,但我正在讨论应该如何创建对象。目前我有一些 AssetManager 类保存对创建的每个对象的引用,检查现有 ID 并只允许唯一的 ID,但这仍然没有解决被迫在管理类外部生成 ID 的问题。这让我认为工厂是最好的方法。

我知道在 C# 中我可以创建一个 AssetFactory<T> where T:Asset可以轻松地为每个 Assets 调用适当的构造函数来创建实例,但据我所知,C++ 没有这样的设施。

所以我认为我应该采取的方法是使用某种抽象的 AssetFactory。 的想法(正确与否)是 AssetFactory 的子级将跟踪正在使用的 ID,并且只发布适当的对象唯一 ID。像这样:

class Asset {
int m_index;
Asset(int index);
};
class Image : public Asset {
Image(char* imgPath);
void Draw();
};
class Sprite : public Asset {
Sprite(Image* img);
void Draw();
};

class AssetFactory {
private:
std::vector<Asset*> m_assets;
int GetUniqueID();
public:
AssetFactory();
~AssetFactory();

virtual Asset* CreateAsset(); // but each class has different constructor parameters...
};

class ImageFactory : public AssetFactory {
Asset* CreateAsset(char* imgPath); // ...so this wouldn't work (nor compile)
};
class SpriteFactory : public AssetFactory {
Asset* CreateAsset(); // ...so will i be forced to call the default constructor and modify it later?
};

这里的问题是,如上所述,不同的对象有不同的构造函数,使这个设计没有实际意义。我应该采取不同的方法吗?还是我对工厂模式的理解有误?

编辑:为了澄清,我想要为 Sprites 和 Images 单独工厂的原因是 允许 Sprite 和图像具有相同的 ID。 ID 只能在相同“类型”的其他 Assets 中是唯一的。

最佳答案

如果您的库允许任意 ID 并且您在相对相等的地址空间(例如 sizeof(int) == sizeof(int*))中工作,那么这是一个需要解决的非常微不足道的问题,这几乎适用于所有我知道的 32 位编译器。然后生成 ID 就很简单了——只需重新解释_cast 指针即可。

class Sprite {
int GetUniqueID() { return reinterpret_cast<int>(this); } // easies
public:
// public interface
};

此外,重新使用旧 ID 实际上可能不值得。只是继续制作新的。我的意思是,您不会用完 32 位整数的空间。

最后,你绝对不能在这里使用运行时继承。如果必须,请使用编译时混入。

关于c++ - 对象管理——容器还是工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7738819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com