如何将static const变量保持为类的成员

Sij*_*ith 4 c++ qt qt4 visual-c++

我想保持一个静态const变量作为类的成员.是否可以保留,如何启动该变量.

有人说这个有帮助

 QString <ClassName>::ALARM_ERROR_IMAGE = "error.png";
Run Code Online (Sandbox Code Playgroud)

初始化const数据的值

我试过这样的

在CPP班我写

static  QString ALARM_WARNING_IMAGE ;
Run Code Online (Sandbox Code Playgroud)

在构造函数中我写

ALARM_WARNING_IMAGE        = "warning.png";
Run Code Online (Sandbox Code Playgroud)

但是没有工作......请提供一些提示来帮助

Ron*_*del 10

在源文件中的任何函数之外写:

const QString ClassName::ALARM_WARNING_IMAGE = "warning.png";
Run Code Online (Sandbox Code Playgroud)

标题:

class ClassName {
  static const QString ALARM_WARNING_IMAGE;
};
Run Code Online (Sandbox Code Playgroud)

另外,不要在构造函数中写任何东西.这将在每次ClassName被实例化时初始化静态变量...这不起作用,因为变量是const ...坏主意可以这么说.只能在声明期间设置一次.


Chu*_*dad 3

这是基本思想:

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(){
}
Run Code Online (Sandbox Code Playgroud)