K时,我这里有一个基类和众多的派生类。下面的基类,在同一文件中,我有一对夫妇登记在地图对象派生的对象std :: string的指标,负责对象,然后将实例化的对象,给予有效的字符串索引的对象。注册一个类的对象,我宣布的类型DerivedRegister的对象在派生类的私有成员,一个类的模板参数,然后调用它的外部类的构造函数。够简单吧?错了。因为对象的方式成立,并宣布,我把语法错误时,调整的基类sligthly。在这里我的base.h是:
#ifndef BASE_H
#define BASE_H
#include <map>
#include <string>
#include <fstream>
using namespace std;
class base{
#define DECLARE_ENTITY(T) static DerivedRegister<T> reg;
#define LINK_ENTITY(T, name) DerivedRegister<T> T::reg(name);
public:
int getMeh() {return m_meh;}
virtual void GetParams(fstream & stream);
protected:
int m_meh;
string m_EntityName;
};
template<class T> base * createT() {return new T;}
class BaseFactory{
public:
typedef map<string, base *(*)()> map_type;
static base * createInstance(const string & s) {
if ( !getMap()->count(s) )
return NULL;
map_type::iterator it = getMap()->find(s);
return it->second();
}
protected:
static map_type * getMap() {
if(!m_Map) {m_Map = new map_type;}
return m_Map;
}
private:
static map_type * m_Map;
};
template<class T>
class DerivedRegister : BaseFactory {
public:
DerivedRegister(std::string const & s)
{
getMap()-> insert( pair<string, base*(*)()> (s, &createT<T>));
}
};
BaseFactory::map_type * BaseFactory::m_Map = new map_type();
#endif
这里是base.cpp当我试图定义一个基地成员:
然而,由于某些原因,我得到这个错误讯息:
base.cpp线5:多个BaseFactory的定义:: m_Map
main.cpp的第11行:第一次在这里定义
这里是我的main.cpp我在那里测试的实例化:
#include <iostream>
#include <vector>
using namespace std;
#include "base.h"
#include "derived.h"
#include "second.h"
#include "third.h"
#include "fourth.h"
int main()
{
BaseFactory yosh;
vector<base *> meh;
for(int i = 0; i < 20; i++)
{
if(i % 4 == 0)
meh.push_back(yosh.createInstance("derived"));
else if( i % 4 == 1)
meh.push_back(yosh.createInstance("second"));
else if( i % 4 == 2)
meh.push_back(yosh.createInstance("third"));
else
meh.push_back(yosh.createInstance("fourth"));
}
for(int i = 0; i < (int) meh.size(); i++)
{
if(meh[i])
cout << meh[i]->getMeh() << "\n";
else
cout << "invalid\n";
}
for(int i = 0; i < (int) meh.size(); i++)
{
if(meh[i]) delete meh[i];
}
return 0;
}
派生的,第二,第三和第四的都只是测试类,除了有构造分配不同的价值观,以m_Meh相同。这是很有启发。无论如何,我有这个错误,是问题的那一刻,我省略,虚函数,基类GetParams,然后省略基本上一切内base.cpp文件,编译和工作得很好。所以这是为什么,当我尝试和基类添加一个方法,我得到重新定义m_Map错误?
编辑:我意识到刚才的basefactory地图可能需要作出一些澄清。在那里m_map对象类型std :: string的指标,那么指数指函数的指针。函数的定义只以上的有类。派生类注册时,他们通过自己的类,模板参数和一个const的字符串。这些都是在一个新的地图对象常量字符串和模板函数指针是成对在一起指数。看到我然后随时调用成员创建的实例,它通过在常量字符串,如果有一个有效的索引,如果有,它返回在该指数中,这就是所谓的功能,并返回一个新的对象实例注册到该常量字符串。| FatalCatharsis