我试图实现单例模式,假设只使用私有构造函数,类的私有实例和公共静态方法来返回实例 . 但我在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() {
}
我想知道错误的原因以及为什么需要在类外部显式编写构造函数 .
4 回答
在类中,构造函数仅被声明,未定义 . 定义包括函数体 . 它没有隐含地
inline
.在其他新闻中:
Singletons通过避免例如改进全局变量来改进全局变量静态初始化顺序为fiasco,但对于不可见的通信线路和副作用存在同样的问题 . 最好避免 .
如果在销毁相应的全局变量后不需要单例来保持,那么只需使用简单的Meyers单例 .
这是迈耶斯的单身人士:
默认构造函数需要一个主体:
你可以改变
至
在课堂内,它应该工作 .
在迈耶的单身人士的演变中,我更喜欢 Value 语义单例,原因在下面的代码中提到:
帕加达拉是对的 . 缺少构造函数定义,因此链接器错误