我正在编写一个简单的c ++工厂,但我得到一个我不理解的错误。 这是我的班级定义:
MSGFactory.hpp
class MSGFactory
{
public:
static MSGFactory * getInstance();
void registerMSG(const std::string MSGType , createMSGFn constructor );
MSGData *createMessage(const std::string &MSGType);
private:
static MSGFactory * inst;
std::map<std::string,createMSGFn> MSGPool;
};
这是它的实现:
MSGFactory.cpp
MSGFactory * MSGFactory::getInstance()
{
if(inst == NULL) inst = new MSGFactory();
return inst;
}
void MSGFactory::registerMSG(const std::string MSGType , createMSGFn constructor )
{
MSGPool.insert(factoryBucket(MSGType,constructor));
}
MSGData * MSGFactory::createMessage(const std::string &MSGType)
{
std::map<std::string,createMSGFn>::iterator it;
it = MSGPool.find(MSGType);
if( it != MSGPool.end() )
return it->second();
return NULL;
}
我写了这个测试程序:
T_MSGFactory.cpp
class MSGOne : MSGData
{
public:
MSGOne(){}
~MSGOne() {{std::cout<<"Derived destructor called\n";}}
std::string type() { std::cout << "Type One" << std::endl; return " ";}
unsigned char* getData(){ return (unsigned char *) "a"; }
static MSGData * Create() { return new MSGOne(); }
};
class MSGTwo : MSGData
{
public:
MSGTwo(){}
~MSGTwo() {std::cout<<"Derived destructor called\n";}
std::string type() { std::cout << "Type Two" << std::endl; return " ";}
unsigned char* getData(){ return (unsigned char *) "a"; }
static MSGData * Create() { return new MSGTwo(); }
};
class MSGThree : MSGData
{
public:
MSGThree(){}
~MSGThree() {std::cout<<"Derived destructor called\n";}
std::string type() { std::cout << "Type Three" << std::endl; return " ";}
unsigned char* getData(){ return (unsigned char *) "a"; }
static MSGData * Create() { return new MSGThree(); }
};
int main(int argc, char **argv)
{
std::cout << "PROVA" << std::endl;
MSGFactory::getInstance()->registerMSG("ONE", &MSGOne::Create );
MSGFactory::getInstance()->registerMSG("TWO", &MSGTwo::Create );
MSGFactory::getInstance()->registerMSG("THREE", &MSGThree::Create );
return 0;
}
但用“g ++ T_MSGFactory.cpp MSGFactory.cpp”编译它我收到此错误:
1)“riferimento non definito a”是“未定义的参考”
2)“nella funzione”是“在功能上”
有人能帮助我吗?感谢
答案 0 :(得分:2)
在MSGFactory.cpp文件的顶部,就在include之后,在全局范围内,您应该声明静态成员。
像这样:MSGFactory* MSGFactory::inst=NULL;
答案 1 :(得分:2)
必须定义静态成员变量,通常在源文件中。
将其添加到您的MSGFactory.cpp
MSGFactory* MSGFactory::inst = 0;
http://www.learncpp.com/cpp-tutorial/811-static-member-variables/