我正在尝试为类创建静态常量成员。现在,我有这个基于 C# 方式的函数:
class Question : public QObject
{
Q_OBJECT
friend class Answer;
public:
static const QMap<QString /*name*/, QPair<QList<quint8> /*data*/, qint32 /*answerSize*/>> questionMap()
{
return {
{
"check digit",
{
{
0xF0, 0xC0, 0x4F
},
3
}
},
{
"line detect",
{
{
0xF0, 0xE0, 0x2F
},
79
}
}
};
}
static const Question& createQuestion(const QString& questionName) {
Question* question = new Question(questionName,
Question::questionMap()[questionName].first,
Question::questionMap()[questionName].second);
return *question;
}
我希望有更多这样的东西:
static const QMap<QString /*name*/, QPair<QList<quint8> /*data*/, qint32 /*answerSize*/>> questionMap =
{
{
"check digit",
{
{
0xF0, 0xC0, 0x4F
},
3
}
},
{
"line detect",
{
{
0xF0, 0xE0, 0x2F
},
79
}
}
};
因为我不确定第一种方法在内存管理方面看起来如何...这个函数只调用一次并且两个想法之间没有区别还是从第一个函数返回的对象被一遍又一遍地创建并且使用第二种方法更有效?无论如何,当我尝试使用值(value)时,它会:
field initializer is not constant
in-class initialization of static data member of non-literal type
non-constant in-class initiualization invalid for static member
(an out of class initialization is required)
cannot be initialized by a non-constant expression when being decalred
当然,当我将初始值设定项移出类时它会起作用,但是......究竟是为什么?有没有办法绕过它?我应该绕过它吗?方便使用此值的最合适方法是什么?
最佳答案
非文字类型的 static const
数据成员必须具有类外定义才能满足单一定义规则:Why can't I initialize non-const static member or static array in class?
当您访问非文字类型的 static const
数据成员时,该成员绑定(bind)到 const
引用或隐式 const this
参数,所以它必须有一个内存位置;这可以通过类外定义来满足,否则将没有单一定义来提供其内存位置。
拥有返回对象的 static
成员函数可能效率低下,因为每次调用 static
成员函数时都必须重新创建对象。
关于c++ - "static property"和静态常量值有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24992256/