2009-04-13 160 views

回答

53

您必須添加在實施文件中的以下行:

int Foo::bar = you_initial_value_here; 

這是必需的,因此編譯器提供了靜態變量的地方。

16

這是正確的語法,但Foo::bar必須單獨定義,在頭之外。在您的.cpp文件中的一個,這樣說:

int Foo::bar = 0; // or whatever value you want 
+0

Hello Chris,如果我們在C++中有這麼多的公共靜態類成員變量(非多線程源代碼),是否有什麼錯誤?我已經將一些全局變量作爲公共靜態移動到一個類中。 – sree 2015-05-26 15:02:55

15

您需要添加一行:

int Foo::bar; 

這將定義你的存儲。類中靜態的定義類似於「extern」 - 它提供了符號,但不創建符號。即

foo.h中

class Foo { 
    static int bar; 
    int adder(); 
}; 

Foo.cpp中

int Foo::bar=0; 
int Foo::adder() { ... } 
1

用於類的靜態變量,在首先你必須向你的靜態變量generaly(無localy)給出一個值(初始化),那麼你可以在類中訪問一個靜態成員:

class Foo 
{ 
    public: 
    static int bar; 
    int baz; 
    int adder(); 
}; 

int Foo::bar = 0; 
// implementation 
int Foo::adder() 
{ 
    return baz + bar; 
}