Initilizing value for a const data

2019-08-06 11:29发布

Following code is in my c++ class

static const  QString ALARM_ERROR_IMAGE ;

i want to initilize

ALARM_ERROR_IMAGE          = "error.png";

Is it possible to initilize error.png to static const QString ALARM_ERROR_IMAGE Want to keep it inside class

2条回答
可以哭但决不认输i
2楼-- · 2019-08-06 12:16

Static variable of a class have to be defined explicitly in the namespace scope only once (irrespective of wheter they are further cv qualified or not).

In the .cpp file (e.g in <ClassName>.cpp), in the global namespace (assuming your class is in global namespace), define it as follows (assuming an appropriate constructor exists in QString)

NB: I missed 'const' in the definition below

const QString <ClassName>::ALARM_ERROR_IMAGE = "error.png";

$9.4.2/2 - "The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator."

查看更多
做个烂人
3楼-- · 2019-08-06 12:29

Not possible to keep inside. Only const static integral data members are allowed to initialized inside a class or struct.

查看更多
登录 后发表回答