C++工厂实现麻烦

标签 c++ static function-pointers factory-pattern

我正在编写一个简单的 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"是 "功能正常"

compiling error

有人可以帮助我吗?谢谢

最佳答案

在 MSGFactory.cpp 文件的顶部,就在包含之后,在全局范围内,您应该声明静态成员。

像这样:

MSGFactory* MSGFactory::inst=NULL;

关于C++工厂实现麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745197/

相关文章:

c++ - 这是缓冲的正确大小吗?

c++ - `*a` 和 `a[0]` 有什么区别?

c++ - Visual C++ Express 2008 的静态运行时库链接

c++ - 使用传递函数指针调用 _beginthreadx

matlab - 从函数句柄获取文档

c++ - 使用 &MyClass::MyFunction 时出现 undefined reference 链接错误

c++:使用模板将任何lambda包装在另一个lambda中

c++ - 在 Visual Studio 2017(VC++) 的链接阶段禁用库警告是否安全?

java - 如何在 Spring 中保留静态类变量的值?

css - Django外部css文件问题