我正在尝试实现模板单例模式,但是我收到了以下错误。我该如何克服这个错误?
下面是singleton_template.h
#include <iostream>
#include <string>
/*
* Burada yapılan herşey ".h" dosyası içerinde olmalı
*/
template<typename T>
class Singleton
{
private:
static T* _instance;
Singleton(const Singleton&);
Singleton & operator=(const Singleton& rhs);
protected:
Singleton();
public:
static T* getInstance()
{
if(!_instance)
_instance = new T;
return _instance;
}
void destroyInstance()
{
delete _instance;
_instance = NULL;
}
};
template<typename T>
T* Singleton<T>::_instance= NULL;
这是singleton_template.cpp
#include <iostream>
#include <string>
#include "singleton_template.h"
class GKM : public Singleton<GKM>
{
public:
GKM()
{
std::cout << "Single GKM created"<<std::endl;
}
virtual void initialize(){return;}
};
class Turnstile: public GKM
{
public:
Turnstile(){std::cout << "Single turnstile created add: "<< this<<std::endl;}
virtual void initialize(){std::cout <<"Turnstile"<< std::endl;}
};
int main()
{
GKM* trn= Turnstile::getInstance();
trn->initialize();
return 0;
}
以下是编译失败后的结果:
/tmp/ccfD0Xgx.o:在函数
GKM::GKM()
中: singleton_template.cpp :(。text._ZN3GKMC2Ev [_ZN3GKMC5Ev] + 0xd):undefined 引用Singleton<GKM>::Singleton()
collect2:error:ld 返回1退出状态
答案 0 :(得分:1)
您没有实现Singleton
类的默认构造函数,因为您继承了Singleton
类,所以需要它。你可以改变
Singleton();
行到
Singleton() {}
然而,当我阅读你的代码时,它无论如何都不会按预期工作,因为
GKM* trn= Turnstile::getInstance();
实际上只创建了GKM
个对象,而不是Turnstile
,因为Singleton
上有GKM
,而Turnstile
上没有import os
import glob
import re
my_dir = 'whatever dir'
special_filelist = dict()
filelist = []
os.chdir( my_dir )
for files in glob.glob( "*.csv" ) :
filelist.append(files)
fileListName = re.match(r'(.*)[0-9]', files).group(1)
if (fileListName not in special_filelist):
special_filelist[fileListName] = []
special_filelist[fileListName].append(files)
print special_filelist
。 (或者这是打算?)