【发布时间】:2016-08-15 12:53:12
【问题描述】:
我试图实现单例模式,假设只使用私有构造函数、类的私有实例和公共静态方法来返回实例。但是我在Visual Studio中遇到了以下代码的错误
// Singleton Invoice
#include <iostream>
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() {
}
我想知道错误的原因以及为什么需要在类之外显式编写构造函数。
【问题讨论】:
-
我认为这是因为您声明了构造函数但没有实现它。顺便说一句,你是范莎学院的学生吗?只是好奇
-
您正在创建指向您的 getInstance 方法和单例对象的指针。您是否尝试过在 main 中取消引用?
-
@kburlz 我是布里奇波特大学的学生 :D ,这是我的教授在互联网上找到的一个例子来教我们单例模式,所以当我自己编写它时,我遇到了问题并且很好奇。我想您可能已经通过相同的示例进行了教学:D
-
@almostcolin 当我第一次看到错误时,我在想编译器可能无法区分静态对象和 get 方法,所以当我回顾讲座幻灯片时,我注意到了构造函数明确指定
标签: c++ design-patterns