我试图实现单例模式,假设只使用私有构造函数,类的私有实例和公共静态方法来返回实例 . 但我在Visual Studio中遇到以下代码的错误
// Singleton Invoice
#include
using namespace std;
class Singleton {
public:
//Public Static method with return type of Class to access that instance.
static Singleton* getInstance();
private:
//Private Constructor
Singleton();
//Private Static Instance of Class
static Singleton* objSingleton;
};
Singleton* Singleton::objSingleton = NULL;
Singleton* Singleton::getInstance() {
if (objSingleton == NULL) {
//Lazy Instantiation: if the instance is not needed it will never be created
objSingleton = new Singleton();
cout << "Object is created" << endl;
}
else
{
cout << "Object is already created" << endl;
}
return objSingleton;
}
int main() {
Singleton::getInstance();
Singleton::getInstance();
Singleton::getInstance();
return 0;
}
错误如下:
LNK2019未解析的外部符号“private:__thiscall Singleton :: Singleton(void)”(?? 0Singleton @@ AAE @XZ)在函数“public:static class Singleton * __cdecl Singleton :: getInstance(void)”中引用(?getInstance @ Singleton @@ SAPAV1 @ XZ)
然后我解决了错误,但重写了类外的构造函数
Singleton::Singleton() {
}
我想知道错误的原因以及为什么需要在类外部显式编写构造函数 .