需求: 希望根据用户的输入调用同名的函数。
因为不想写各种 if else,所以就建立一个key为string,value为函数指针的map,根据string的值调用相应的函数。
以下代码在gcc 3.4.6下测试通过。
下面是代码的第一次实现:
<code>
#include<iostream>
#include<map>#include<string>
void buildMap();
class Image{
public:
Image() {}
void func1() { std::cout << "func1 called.\n"; }
void func2() { std::cout << "func2 called.\n"; }
};
typedef void (Image::*pfunc)(); // define function pointer type
std::map<std::string, pfunc> strFuncMap;
void buildMap() { strFuncMap["func1"] = &Image::func1; strFuncMap["func2"] = &Image::func2; }
void callFunc(Image& img, const std::string& str) { if(strFuncMap.count(str)) (img.*strFuncMap[str])(); else std::cout << "unsupported function str.\n";}
int main() {
Image img;
buildMap();
callFunc(img, "func1");
callFunc(img, "func3");
return 0;
}
</code>
但是这样用的是一些自由函数和变量,我想把它们放到类里面去。因为我觉得不需要每一个对象都建立一个map,所以把该map设置成了static类型。
注意加红的部分 (