C++动态创建和构造派生类

方法一:如果你的类命名是有统一的前缀,如 C, C1, C2, C3 可用宏来创建 

class C
{
public :
	virtual void run() = 0;
};

class C1 : public C
{
public :
	void run() { printf("C1 run\r\n"); }
};

class C2 : public C
{
public :
	void run() { printf("C2 run\r\n"); }
};

#define NEW_C_INSTANCE(class_id) new C##class_id();

int main()
{
	//int id = 2; //不可以这样
	//C* c = NEW_C_INSTANCE(id);
	
	//C* c = NEW_C_INSTANCE(1);
	C* c = NEW_C_INSTANCE(2);
	
	c->run();
	getchar();
	return 0;
}


优点:编译期确定类型,代码高效。
缺点:需要有统一的命名前缀。
      NEW_C_INSTANCE 的参数不能外部指派,只能写固定代码。
      相关头文件需预先定义好,灵活性较差。


方法二:利用静态函数指针创建


class S;

typedef S* (*s_creator_function)(); 

class S
{
public:
	static S* create(){	return NULL;}
	virtual void run() = 0;
};

class S1 : public S
{
public:
	static S* create(){ return new S1();}
	void run() {printf("S1 run!\r\n");}
};

class S2 : public S
{
public:
	static S* create(){	return new S2();}
	void run() {printf("S2 run!\r\n");}
};

class S_Factory
{
public:
	void registerCreator(int id, s_creator_function func )
	{
		map.insert( std::pair<int,s_creator_function>(id, func) );
	}

	S* create(int id)
	{
		std::map<int, s_creator_function>::iterator it;  
		it = map.find(id);//在map中查找创建函数
		if( it != map.end() )
			return (it->second)();
		return NULL;
	}

private:
	std::map<int, s_creator_function> map;
};

S_Factory sFactory;

int main()
{
	sFactory.registerCreator(1, S1::create);
	sFactory.registerCreator(2, S2::create);

	//int n = 1;
	int n = 2;
	S* s = sFactory.create(n);
	s->run();

	getchar();
	return 0;

}

优点:扩展灵活。
缺点:创建时略显繁锁。规则和管理不好,出错时不好查。

猜你喜欢

转载自blog.csdn.net/RoadToTheExpert/article/details/8939105