Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中初始化类内的非原语静态数据类型+; #包括 #包括 类Util{ 公众: 静态队列链接; Util(){ } }; Util::links.enqueue(“hello world”);_C++_Qt_Class_Static Members - Fatal编程技术网

C++ 在C+中初始化类内的非原语静态数据类型+; #包括 #包括 类Util{ 公众: 静态队列链接; Util(){ } }; Util::links.enqueue(“hello world”);

C++ 在C+中初始化类内的非原语静态数据类型+; #包括 #包括 类Util{ 公众: 静态队列链接; Util(){ } }; Util::links.enqueue(“hello world”);,c++,qt,class,static-members,C++,Qt,Class,Static Members,我如何才能做到这一点?您可以像往常一样在全局范围内初始化: #include <QQueue> #include <QString> class Util { public: static QQueue<QString> links; Util() { } }; Util::links.enqueue("hello world"); QQueue Util::links; 或 QQueue Util::links

我如何才能做到这一点?

您可以像往常一样在全局范围内初始化:

#include <QQueue>
#include <QString>

class   Util {
public:

    static QQueue<QString> links;

    Util() {
    }
};

    Util::links.enqueue("hello world");
QQueue Util::links;

QQueue Util::links(1);//如有必要,使用构造函数参数

尝试使用静态成员函数:

QQueue<QString> Util::links(1); // with constructor parameters if necessary
QQueue<QString> Util::links = {"hello world"};
#包括
#包括
类Util{
公众:
静态QQueue&links(){
静态QQueue实例;
静态bool是_init=false;
如果(!is_init){
enqueue(“hello world”);
is_init=真;
}
返回实例;
}
Util(){
}
};
在C++11中,QQueue似乎支持初始值设定项列表,正如Shahbaz所说:

#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() {
    }
};
QQueue Util::links={“hello world”};

您可以使用函数的结果对其进行初始化:

QQueue<QString> Util::links(1); // with constructor parameters if necessary
QQueue<QString> Util::links = {"hello world"};
QQueue make_links(){
队列;
排队(“你好世界”);
返回队列;
}
QQueue Util::links=生成链接();
我不熟悉QT,但有人可能希望他们添加了对C++11初始化器列表的支持,在这种情况下,您可以将其初始化为:

QQueue<QString> make_links() {
    QQueue<QString> queue;
    queue.enqueue("hello world");
    return queue;
}

QQueue<QString> Util::links = make_links();
QQueue Util::links{“hello world”};

(更新:根据Shahbaz评论中的链接,如果您使用的是C++11,您确实可以这样做)。

您可以对所有此类情况使用静态初始值设定项对象:

头文件:

QQueue<QString> Util::links {"hello world"};

除了
“你好,世界”
不在那里!另外,如果没有在多线程程序中可用的构造函数或程序,您需要确保在允许多个线程访问它之前对其进行初始化。静态对象没有这个问题。@MikeSeymour是的,静态成员函数不是解决这个问题的好方法。
namespace {
    struct StaticInitializer {
        StaticInitializer() {
            Util::links.enqueue("hello world");
        }
    } initializer;
}