2012-02-15 280 views
-1

有人可以幫助我理解,爲什麼在下面的類中定義的static變量masterID重新初始化,是否創建了具有非默認構造函數的新實例?靜態變量重新初始化

static unsigned int masterID=0; 

class game{ 
public: 
    unsigned int m_id; 
    unsigned int m_players; 

    // default constructor 
    game():m_id(masterID++){ 

    } 

    // another constructor using a game instance 
    game(game g): m_id(masterID++){ 
    ... 
    } 

    // copy constructor 
    // copy constructor 
    game(const game &o) 
    : m_id(o.m_id), m_players(o.m_players) 
    { } 

    // assignment operator 
    game& operator =(const game o){ 
    m_id = o.m_id; 
    m_players = o.m_players; 
    return *this; 
}; 

與此代碼,只要創建使用默認構造

情況下,例如

game g1, g2; 

的M_ID呈現值0,1,2,...等等。

但是,如果現在我創建第三個實例作爲

game g3(g2); 

爲G3的M_ID再次爲0

我不明白這裏發生了什麼。

+5

的'靜態無符號整型masterID = 0;'線是不** **在'.H '文件,是嗎? – dasblinkenlight 2012-02-15 19:59:22

+2

[Works just fine](http://ideone.com/Mhy6l)如你所示,顯然問題在於你沒有顯示的代碼。 [SSCCE](http://sscce.org) – ildjarn 2012-02-15 20:03:13

+2

你在告訴我們所有的事實嗎?我試過你的代碼,第二個構造函數不重置masterID。但我需要修復myID標識符,所以這不是真正的代碼。 – 2012-02-15 20:11:07

回答

2

這是因爲static unsigned int masterID=0;在您的.h文件中。它不應該在那裏:你現在的方式,你得到一個單獨的靜態變量在每個編譯單元,其中包括您的.h文件。

做的正確方法是聲明masterID靜態類,並在一個單一的.cpp文件初始化。

在你h文件:

class game{ 
public: 
    unsigned int m_id; 
    unsigned int m_players; 
    static unsigned int masterID; // no initialization! 

    // default constructor 
    game():m_id(masterID++){ 

    } 

    // another constructor 
    game(unsigned int players): m_id(masterID++), m_players(players){ 

    } 
}; 

在您的CPP文件:

game::masterID = 0; 
+0

問題仍然存在於一個新的實例中,使用前一個創建的實例,使用'game gNew(gExisting)' – 2012-02-15 21:38:30

+1

@NikhilJJoshi您的構造函數'game(遊戲g):m_id(masterID ++)'可疑,它不應該在那裏。如果你想要的效果是讓拷貝獲得一個新的ID,你應該在拷貝構造函數中設置它。我假設你從.h文件中刪除了獨立的'static unsigned int masterID = 0;'行,對吧? – dasblinkenlight 2012-02-15 21:55:46