QString : 非文字类型静态数据成员的类内初始化

QString : inclass initialization of static data member of non-literal type

大家好

请注意:c++新手

我已经开始了一个项目来尝试发现 c++ 的各个方面,目前我正忙于创建一个动态库。 Class姓名misc

在我的 misc.h 中,我有几个 QString 的其他对象。

问题:

错误:

misc.h:17: error: in-class initialization of static data member 'QString

Misc::googleDNS' of non-literal type

static QString googleDNS = QString("8.8.8.8");

                                        ^

据我所知,从另一个 class 调用静态对象是由 class::static_variable 完成的。因此我尝试了同样的方法:

这是我的问题的基本代码示例:

//misc.h

#include "misc_global.h"
#include <QString>

class MISCSHARED_EXPORT Misc
{
public:
    static QString googleDNS = QString("8.8.8.8");
    static QString ...
};

应用示例:

//netm.h

#include "../misc/misc.h"
//...

class NETMSHARED_EXPORT netm
{
    netm();
    ...
};

//netm.cpp

//...
QHostAddress ip = QHostAddress(Misc::googleDNS);
//...

在寻找解决方案时,我尝试了 constconstexprstatic 的各种组合,显然都没有奏效。

我找不到对非文字含义的可靠解释,

不胜感激!

你不能在头文件中初始化一个QString

在你的misc.h

class MISCSHARED_EXPORT Misc
{
public:
    static QString googleDNS;
    static QString ...
};

misc.cpp 或您包含的某个地方 misc.h 执行此操作

QString Misc::googleDNS = QString("8.8.8.8");

How can I initialize the static QString member of the class?

best way to initialize the QString 正在使用 QStringLiteral:

// in my.h file:
class Misc
{
public:
    static QString s_myQString;
};

// in my.cpp file:
QString Misc::s_myQString = QStringLiteral("String...");

这样我们就避免了动态分配直到字符串内容改变。