[英]template class of static const member variable vs static const member variable initialization
[英]How to keep static const variable as a member of a class
我想保留一个静态常量变量作为类的成员。 是否可以保留以及如何初始化该变量。
一些身体帮助说这个
QString <ClassName>::ALARM_ERROR_IMAGE = "error.png";
我试过这样
在 CPP 课上我写
static QString ALARM_WARNING_IMAGE ;
在构造函数中我写
ALARM_WARNING_IMAGE = "warning.png";
但不工作......请提供一些提示帮助
在源文件中的任何函数之外写入:
const QString ClassName::ALARM_WARNING_IMAGE = "warning.png";
这种结构也有效:
const QString ClassName::ALARM_WARNING_IMAGE("warning.png");
标题:
class ClassName {
static const QString ALARM_WARNING_IMAGE;
};
另外,不要在构造函数中写任何东西。 这将在每次实例化 ClassName 时初始化静态变量。 这不起作用,因为变量是 const 并且可以这么说是个坏主意。 consts 只能在声明期间设置一次。
这是基本思想:
struct myclass{
//myclass() : x(2){} // Not OK for both x and d
//myclass(){x = 2;} // Not OK for both x and d
static const int x = 2; // OK, but definition still required in namespace scope
// static integral data members only can be initialized
// in class definition
static const double d; // declaration, needs definition in namespace scope,
// as double is not an integral type, and so is
// QSTRING.
//static const QString var; // non integral type
};
const int myclass::x; // definition
const double myclass::d = 2.2; // OK, definition
// const QString myclass::var = "some.png";
int main(){
}
尝试:
QString ClassName::ALARM_WARNING_IMAGE = "warning.png";
只允许在类或结构中初始化 const 静态整数数据成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.