2013-07-17 51 views
13

我有一個關於選擇哪個函數來初始化靜態類成員的問題。哪個函數用於初始化靜態類成員?

//Base.h 

class Base 
{ 
private: 
    static int count; 
    static int countInit() 
    { 
     return 10; 
    } 
public: 
    Base() 
    { 
    } 
}; 

//and Base.cpp 
static int countInit() 
{ 
    return 0; 
} 
int Base::count=countInit();//member function is used. 
static int local_count=countInit();//the local one in Base.cpp 

可變Base::count被初始化爲Base::countInit()而非Base.cpp定義的countInit()。但local_count由本地countInit初始化。所以,我想知道,在這種情況下是否有像Koenig lookup的規則?

+0

所以'INT基準::計數= countInit() ;'調用成員? –

+1

@LuchianGrigore,是的,它的確如此。我不知道發生了什麼事。 – chris

+0

其中是「int Base :: count = countInit();」被調用?導致靜態成員函數Base :: countInit()計數不會僅由countInit()超出Base類的作用域調用。 – lulyon

回答

17

當你編寫int Base::count後,你在類Base,所以類的靜態函數將被調用。 不合格查找這裏將

用於從3.4.2/13

類X(9.4.2)的靜態數據成員的定義中使用的名稱(靜態的合格-ID後 成員)被查找好象是這個名字是在X的成員函數使用

從9.4.2

的靜態數據成員的定義應該出現在一個命名空間 範圍封閉成員類定義。在名稱空間範圍的定義中,靜態數據成員的名稱應使用::運算符通過其類名進行限定。 在靜態數據成員的 定義的初始化表達是同類的範圍

實施例:

class process { 
static process* run_chain; 
static process* running; 
}; 
process* process::running = get_main(); 
process* process::run_chain = running; 

+0

謝謝。非常清楚。 – Donglei