[英]C++ Factory implementation trouble
我正在编码一个简单的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”是“ undefined reference to”
2)“ nella funzione”在功能上
有人能帮我吗? 谢谢
在MSGFactory.cpp文件的顶部,在全局作用域中的include之后,您应该声明静态成员。
像这样:
MSGFactory* MSGFactory::inst=NULL;
通常必须在源文件中定义静态成员变量。
将此添加到您的MSGFactory.cpp
MSGFactory* MSGFactory::inst = 0;
http://www.learncpp.com/cpp-tutorial/811-static-member-variables/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.