[英]Initialization of non-primitive static data type within class in C++
#include <QQueue>
#include <QString>
class Util {
public:
static QQueue<QString> links;
Util() {
}
};
Util::links.enqueue("hello world");
How can I do that? 我怎样才能做到这一点?
You could initialise it with the result of a function: 您可以使用函数的结果初始化它:
QQueue<QString> make_links() {
QQueue<QString> queue;
queue.enqueue("hello world");
return queue;
}
QQueue<QString> Util::links = make_links();
I'm not familiar with QT, but one might hope that they are adding support for C++11 initialiser lists, in which case you'd be able to initialise it as: 我不熟悉QT,但有人可能希望他们添加对C ++ 11初始化列表的支持,在这种情况下,您可以将其初始化为:
QQueue<QString> Util::links {"hello world"};
(UPDATE: according to the link in Shahbaz's comment, you can indeed do that if you are using C++11). (更新:根据Shahbaz评论中的链接,如果你使用的是C ++ 11,你的确可以这样做)。
Try using a static member function: 尝试使用静态成员函数:
#include <QQueue>
#include <QString>
class Util {
public:
static QQueue<QString>& links() {
static QQueue<QString> instance;
static bool is_init = false;
if(!is_init) {
instance.enqueue("hello world");
is_init = true;
}
return instance;
}
Util() {
}
};
In C++11 QQueue seems to support initializer lists, as Shahbaz has said: 在C ++ 11中,QQueue似乎支持初始化列表,正如Shahbaz所说:
QQueue<QString> Util::links = {"hello world"};
You can use static initializer object for all such cases: 您可以为所有这些情况使用静态初始化对象:
header file: 头文件:
#include <QQueue>
#include <QString>
class Util {
public:
static QQueue<QString> links;
Util() {
}
};
cpp file: cpp文件:
namespace {
struct StaticInitializer {
StaticInitializer() {
Util::links.enqueue("hello world");
}
} initializer;
}
You initialize as usual, in the global scope: 您可以像往常一样在全局范围内初始化:
QQueue<QString> Util::links;
or 要么
QQueue<QString> Util::links(1); // with constructor parameters if necessary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.