2010-09-13 49 views

回答

3

这里的基本思想是:

const QString ClassName::ALARM_WARNING_IMAGE = "warning.png"; 

标题:在源文件中写

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(){ 
} 
+0

注释'var'的任何理由?这似乎意味着它在什么时候无效。 – 2010-09-13 09:32:20

+0

@Mike Seymour:因为我没有QString定义。 – Chubsdad 2010-09-13 12:42:18

0

尝试帮助:

QString ClassName::ALARM_WARNING_IMAGE = "warning.png";

+0

任何需要在C++类中声明 – Sijith 2010-09-13 08:03:27

+0

我想使它保持不变...不给它常量... – Sijith 2010-09-13 08:08:55

+0

如果你使它保持不变,你必须标记*声明*(在类中)和*定义*(这是这个答案显示的)作为'const'。 – 2010-09-13 08:19:32

0

只有量静态整型数据成员被允许类或结构内部的初始化。

8

以外的任何功能的

class ClassName { 
    static const QString ALARM_WARNING_IMAGE; 
}; 

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

+0

非常感谢...它的工作 – Sijith 2010-09-13 08:47:33