/* * map.cpp * * Created on: 2014-8-20 * Author: shopping */ #include <stdio.h> #include <utility> #include <list> #include <map> /*1. 定义一个函数指针*/ typedef void * (* pCreateFun)() ; /*2. 定义一个pair*/ typedef std::pair<char * ,pCreateFun> Tpair; /*3. 定义一个maps*/ typedef std::map<char * , pCreateFun> ObjMap; /*4. 定义一个函数,该函数仅用于测试,故为空*/ static void * CreateInstance(){ } /*5. 定义一个类*/ class LocalOPT { public: static ObjMap * pobjectmap; LocalOPT(char * name,pCreateFun fun) { if(!pobjectmap) { pobjectmap = new ObjMap; printf("sys has create a new Map\n"); } /*6. 执行一个插入操作*/ pobjectmap->insert(Tpair(name,fun)); }; }; /*7. 初始化类中的成员变量*/ ObjMap * LocalOPT::pobjectmap = NULL; /*8. 这个操作很关键,这个操作会初始化LocalOPT类中的成员变量*/ static LocalOPT ingesteropt = LocalOPT("IngestManager", CreateInstance); //注意第二个参数,调用函数指针 bool LoadAppLib() { /*9. appObj = new ObjMap*/ ObjMap * appObj = LocalOPT::pobjectmap; pCreateFun pfun =NULL; ObjMap::iterator mapPtr; if(!appObj) return false;// no app class std::list<char *>AppList; AppList.push_back("A3Interface"); AppList.push_back("IngestManager"); AppList.push_back("ReportManager"); AppList.push_back("OverTimeManager"); AppList.push_back("HeartBeat"); std::list<char *>::iterator ptr; for(ptr = AppList.begin(); ptr != AppList.end(); ptr++) { /*10. 返回的是一个迭代器,如果在appObj中没有查找到*ptr字符串时,就会返回一个NULL*/ mapPtr = appObj->find(*ptr); printf("*ptr = %s \n",*ptr); /*11. 所以在这里只有IngestManager在appObj中能被找到,只会执行CreateInstance这个函数*/ if(mapPtr != appObj->end()) { pfun = mapPtr->second; pfun(); //void * pobj = pfun(); } } return true; } int main(int argc, char ** argv) { LoadAppLib(); return 0; }
原文地址:http://blog.csdn.net/jxnu_xiaobing/article/details/38707351