参考:
原先有静态变量依赖问题,
参考这个,又做了改进:
classfactory.h文件
#ifndef CLASSFACTORY_H#define CLASSFACTORY_H#include #include using namespace std;#include "boardbase.h"typedef void* (*register_func)();class Class{public:static void* newInstance(const string& class_name) {map::iterator it = constructors().find(class_name);if (it == constructors().end())return NULL;elsereturn it->second();}static void registerClass(const string& class_name, register_func func) {constructors()[class_name] = func;}private://避免static初始化顺序问题导致崩溃static map& constructors(){/* key is class name and value is function to create instance of class */static map m_register;return m_register;}};class ClassFactory{public:static BoardBase* createBoardBase(const string& bank_name) {return (BoardBase*)Class::newInstance(bank_name);}};class Register{public:Register(const string& class_name, register_func func) {Class::registerClass(class_name, func);}};//在cpp文件中使用#define REGISTER_CLASS(class_name) \class class_name##Register { \public: \static void* newInstance() { \return new class_name; \} \private: \static Register reg; \};\Register class_name##Register::reg(#class_name,class_name##Register::newInstance);#endif // CLASSFACTORY_H