C++ 静态成员,多个对象 [英] C++ static members, multiple Objects

查看:47
本文介绍了C++ 静态成员,多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 C++ 中的静态成员和方法时遇到了一些麻烦.这是类标题:

I've got some trouble with static members and methods in C++. This is the Class header:

class Decoration {
public:     
    //Static Methods
    static void reloadList();

    //Static Members
    static std::unordered_map<int, Decoration> decorationMapID;
};

在 .cpp 中:

void Decoration::reloadList() {
    sqlTable result = db->exec("SELECT id, name, description FROM decorations");
    for(sqlRow r: result) {
        Decoration::decorationMapID.insert(std::pair<int,Decoration>(atoi(r[0].c_str()), Decoration(r[1], r[2], atoi(r[0].c_str()))));  
    }
}

现在,在我的 mainWindow 类(我使用 QT5)中,我调用 reloadList() 并初始化地图.该列表现在已填充到此对象中.

Now, in my mainWindow class (I'm using QT5), I call reloadList() and initialize the map. The list is now filled in this Object.

在另一个Window-Class中,我想使用这个静态列表,但是列表是空的.你能解释一下我如何必须使用静态成员在任何地方访问同一个列表吗?

In another Window-Class, I want to use this static list, but the list is empty. Could you explain how I have to use the static members to access the same list everywhere?

第二类声明:

在 mainWindow.h 中:

in mainWindow.h:

ShoppingLists slDialog;

在 mainWindow.cpp 中我调用:

in mainWindow.cpp I call:

slDialog.setModal(true);  slDialog.show();

顺便说一句:整个东西是一个 CocktailDatabase,所以我的目标是为 Cocktail-、Ingredient-、Decoration- 和 Taste- 对象提供一个列表/映射,我可以使用它而无需从 SQLite 重新加载它.

Btw.: The whole thing is a CocktailDatabase, so my target is to have a List/Map for Cocktail-, Ingredient-, Decoration-, and Taste- Objects, which I can use without reloading it from SQLite.

推荐答案

1) 静态成员只存在一次,并且在所有 Decoration 实例之间共享.

1) The static member exists only once and is shared between all the instances of Decoration.

2) 问题是为什么它是空的.这里有一些提示:a) 您认为它是空的,因为某些 Windows 对象没有刷新并且不知道您的列表已被填充.
b) 您的窗口在静态列表初始化之前被初始化

2) The question is why it is empty. Here some hints: a) You think it is empty because some windows object was not refreshed and is not aware that your list was poupulated.
b) Your window get initiaslised before the static list is initialised

3) 尽管如此建议:不要让你的静态列表public,特别是如果它必须在使用前初始化.使用确保已初始化的公共访问功能.这是粗略的想法:

3) nevertheless an advice: don't make your static list public, especially if it has to be initialised before it's used. Use a public access function that makes sure it's initialised. Here the rough idea:

class Decoration {
public: 
    std::unordered_map<int, Decoration> getMap(); 

protected:     // or even private ? 
    static void reloadList();
    static bool loaded=false; 
    static std::unordered_map<int, Decoration> decorationMapID;
};

其中 getMap() 类似于:

where getMap() would be something like:

if (!loaded) {
    ... // load the list here
     loaded = true; 
}
return (decorationMapID); 

这篇关于C++ 静态成员,多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆