我試圖讓下面的單例類在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周無法解析的外部
LOL。 'BuildGod'。 – erip
如果您有興趣使它在C++ 11中安全,請參閱http://stackoverflow.com/questions/449436/singleton-instance-declared-as-static-variable-of-getinstance-method。 – BGR