繁体   English   中英

在单个变量中检索差异Qmap

[英]Retrieve differents Qmap in a single variable

我正在使用Qt开发游戏。 我的角色/对象存储在我的模型类中(我尝试遵循MVC模型)。

我创建了一个包含每个对象的QMap:

QMap<int, Safe*> *safes;
QMap<int, Mushroom*> *mushroom;
QMap<int, Floor*> *floors;

但是,然后我想在控制器中检索所有这些QMap并将其从控制器发送到View的paintEvent()类。 有没有办法像这样将QMap存储在QList中:

QList<QMap<int, void*>>

然后施展呢? 我正在寻找一种从单个对象访问这些QMap的方法。

谢谢您的帮助 !

您可以使用结构将它们捆绑在一个对象中:

struct Maps
{
    QMap<int, Safe*> *safes;
    QMap<int, Mushroom*> *mushroom;
    QMap<int, Floor*> *floors;
};

尽管拥有指向QMap的指针是有效的,但是如果您不需要保持指向它的指针,那么我建议您不要这样做。

struct Maps
{
    QMap<int, Safe*> safes;
    QMap<int, Mushroom*> mushroom;
    QMap<int, Floor*> floors;
};

这样,您就不必担心堆分配/释放。

如果您有支持C ++ 11的编译器,则可以使用std :: tuple将项目分组在一起。

std::tuple<QMap, QMap, QMap> maps (safes, mushroom, floors);

首先,是的,您可以为此使用QList ,但是我建议您首先创建一个接口类,并在您的QMap使用它。

struct GameObjectInterface {
};

class Safe : public GameObjectInterface {};
class Mushroom : public GameObjectInterface {};
class Floor : public GameObjectInterface {};

QMap<int, GameObjectInterface*> _GameObjects;

// Is game object with ID `n` a `Safe`?

Safe* s = dynamic_cast<Safe*>(_GameObjects[n]);
if (s != nullptr) {
    // Yes it is a safe
}

另一种可能性:

QList<QMap<int, GameObjectInterface*>> _GameObjects;

而且,如果您愿意,您可以将所有内容封装为一个结构,如其他响应者所暗示的那样。

struct MyGameObject {
    QMap<int, Safe*> Safes;
    QMap<int, Mushrooms*> Mushrooms;
    QMap<int, Floor*> Floors;
};

QList<MyGameObject> _GameObjects;

如果每个都相关(所有对象都具有相同的键),则可以将其简化为:

struct MyGameObject {
    Safe* _Safe;
    Mushrooms* _Mushroom;
    Floor* _Floor;
};
QMap<int, MyGameObject*> _GameObjects;

您可以为所有特定对象保留指向基类的指针:

QMap<int, MyBaseClass*> allObjects;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM