2012-07-11 36 views
4

.cpp文件有一堆類定義。一類有一個私有的靜態成員如下:類定義私有靜態聲明和後續初始化

class SomeClass:public SomeParentClass 
{ 
    private: 
    static int count; 
}; 

權,則計屬性初始化爲0,如下所示:

int SomeClass::count = 0; 

從Java/C#世界來的時候我很難理解count在哪一點被初始化爲零?是什麼時候SomeClass被實例化?此外,班級定義中的count類型爲int,爲什麼SomeClass::count必須在其前面有int

我的最後一個問題是,由於count屬性是私有的,當它在類定義之外初始化時,它的可見性不應該被限制嗎?

感謝

回答

4
  1. 靜態成員初始化in arbitrary order在程序的啓動
  2. static int count;在班上是你的靜態變量的聲明,而int SomeClass::count = 0;是其定義。 C++中的所有定義都需要指定一個類型。
  3. 計數的定義似乎發生在文件範圍內,因此聲明的SomeClass::count的實際範圍保持不公開。
3

類靜態變量將表現爲程序啓動時,如果它被初始化爲0。它獨立於類實例化。

C++語言在聲明中的標識符之前需要一個類型。

用於初始化類靜態變量的C++語法使其看起來像全局變量,但在編譯期間強制訪問變量。

3
Is it when the SomeClass is instantiated?

沒有,你可以通過SomeClass::count訪問它(假設功能有權SomeClass的私有成員)的任何實例之前。在開始製作對象之前它完全可用。


Why does the SomeClass::count has to have an int in front of it?

好,因爲它是一個int。想想當你的函數原型和定義的:

int func (int); 
int func (int i) {return 1;} //you still need the int and (int i) here 
func {return 1;} //NOT VALID - this is what count would be without int 

Since the count attribute is private shouldn't its visibility be 
restricted when it is initialized outside the class definition?

靜態變量的定義是在正常的方式定義時訪問符異常,根據this answer。類的