標籤:
首先static變數只有一次初始化,不管在類中還是在函數中..有這樣一個函數:
1 void Foo() 2 { 3 static int a=3; // initialize 4 std::cout << a; 5 a++; 6 }
裡的static int a=3隻執行了一次。在main中調用Foo()兩次,結果為34.將上面的函數改為
1 void Foo() 2 { 3 static int a; 4 a=3; // not initialize 5 std::cout << a; 6 a++; 7 }
同樣在Foo()中調用兩次.結果為33
在類中使用非const的static類成員變數。初始化時要使用typename classname::variablename = value的形式
例如:
1 class myClass 2 { 3 public: 4 static int a; 5 myClass() 6 { 7 } 8 }; 9 int myClass::a = 3; // here initialize 10 int main() 11 { 12 cout << myClass::a; 13 return 0; 14 }
如果使用的是const類型的static變數,那麼就要在類中初始化:
1 class myClass 2 { 3 public: 4 const static int a=3; // here initialize 5 myClass() 6 { 7 } 8 };
如果是模板中使用非const的static的變數..那需要根據具體類型初始化。
例如 int myClass<int>::a = 4;那麼如果你調用的是cout << myClass<double>::a,那一定會編譯出錯的。
因為模板是不是具體類型,myClass<int>, myClass<double>才是一個具體類型,而一個類靜態成員在特定類中被初始化一次。這樣就好理解了。
原題目: c++ 類中static變數初始化問題
cctt_1
原地址:http://blog.csdn.net/cctt_1/article/details/3979610
c++ 類與函數中static變數初始化問題(轉)