2016-01-23 163 views
0

我試圖讓下面的單例類在C++單在C++編譯錯誤

#pragma once 
#include "stdafx.h" 
#include <iostream> 

class God 
{ 
private: 
    static God* firstObject; 
    God() 
    { 
     if (firstObject != NULL) 
      firstObject = this; 
    } 
public: 
    static God* BuildGod() 
    { 
     if (firstObject != NULL) 
      return firstObject; 
     else { 
      God(); 
      return firstObject; 
     } 
    } 
}; 

,然後用它像這樣

God* a = God::BuildGod(); 

抱歉,系統也不會,甚至將其編譯並返回以下錯誤:

LNK2001無法解析的外部符號「private:static class God * God :: firstObject」(?firstObject @ God @@ 0PAV1 @ A)

LNK1120 1周無法解析的外部

+0

LOL。 'BuildGod'。 – erip

+0

如果您有興趣使它在C++ 11中安全,請參閱http://stackoverflow.com/questions/449436/singleton-instance-declared-as-static-variable-of-getinstance-method。 – BGR

回答

1

你確實有比編譯錯誤糟糕問題,因爲你創建一個臨時對象,並保存一個指針使用它。

聲明

God(); 

創建臨時對象,並在構造函數保存在firstObject一個指向這個臨時對象,你再回來。然後使用該指針將導致未定義的行爲

一個創造了C++一個單身的通常方式會是這樣的:

class God 
{ 
public: 
    static God& get_instance() { 
    { 
     static God instance; // This is THE instance 
     return instance; 
    } 

private: 
    God() {} 
}; 
1

一類的靜態成員必須被定義在類外,像

class God 
{ 
... 
}; 

God* God::firstObj; 

只是提防具有在頭文件中的定義和包括它瑪米時代呼喚麻煩。

+0

聖潔的狗屎男人,工作得很好! 感謝 編輯: 只是試圖添加投操作,以防萬一,如下所示: '運營商爲const char *() \t { \t \t回報 「SUP」; \t}' 它給了我同樣的錯誤再次 – ben

+0

不要得到你的代碼看起來像現在,這工作https://ideone.com/nOIINQ –