求大神帮我看下,这个问题我困扰了半个月
头文件1 dynbase.h #ifndef _DYNBASE_H_ #define _DYNBASE_H_ #include <map> #include <string> using namespace std; typedef void* (*CREATE_FUNC)(); class DynCreateFactory { public: /* ----- 从map容器中得到响应的形状 ----- */ static void* CreateShape(const string& name); /* ----- 运行时动态创建各类形放入map容器 ----- */ static void registes(const string& name, CREATE_FUNC func); private: static map<string, CREATE_FUNC> cls_; }; /* ----- 利用构造函数自动调用DynCreateFactory中的registes函数 ----- */ class RegistObj { public: RegistObj(const string& name, CREATE_FUNC func); }; /* ----- 利用宏定义在main前创建工厂 ----- */ #define CREATE_OBJ(class_name) \ class class_name##Registe { \ public: \ static void* Instance() { \ return new class_name; \ } \ private: \ static RegistObj reg_; \ }; \ RegistObj class_name##Registe::reg_(#class_name, class_name##Registe::Instance) #endif // _DYNBASE_H_ 头文件2 shape.h #ifndef _SHAPE_H_ #define _SHAPE_H_ #include "dynbase.h" #include <iostream> using namespace std; class Shape { public: virtual void Draw() = 0; virtual ~Shape() {} }; class Circle : public Shape { public: virtual void Draw(); ~Circle(); }; class Rectangle : public Shape { public: virtual void Draw(); ~Rectangle(); }; class Square : public Shape { public: virtual void Draw(); ~Square(); }; #endif // _SHAPE_H_ 源文件1 dynbase.cpp #include "dynbase.h" map<string, CREATE_FUNC> DynCreateFactory::cls_; void* DynCreateFactory::CreateShape(const string& name) { map<string, CREATE_FUNC>::iterator it; it = cls_.find(name); if (it == cls_.end()) return 0; else return it->second(); } void DynCreateFactory::registes(const string& name, CREATE_FUNC func) { cls_[name] = func; } RegistObj::RegistObj(const string& name, CREATE_FUNC func) { DynCreateFactory::registes(name, func); } 源文件2 shape.cpp #include "shape.h" void Circle::Draw() { cout << "Circle::Draw()" << endl; } Circle::~Circle() { cout << "~Circle()" << endl; } void Rectangle::Draw() { cout << "Rectangle::Draw()" << endl; } Rectangle::~Rectangle() { cout << "~Rectangle()" <<endl; } void Square::Draw() { cout << "Square::Draw()" <<endl; } Square::~Square() { cout << "~Square()" << endl; } CREATE_OBJ(Circle); //CREATE_OBJ(Rectangle); //CREATE_OBJ(Square); 源文件3 main.cpp #include "shape.h" int main(void) { Shape* sp = (Shape*)DynCreateFactory::CreateShape("Circle"); sp->Draw(); delete sp; return 0; }
#C++工程师#