您的位置:首页 > 其它

运用函数指针和STL的Map实现关键字key与成员函数的映射

2017-03-22 23:36 411 查看
今天的做自动化测试框架的时候发现需要向一个exe传入参数,实现对不同函数的调用,参数是函数名funName,还可以传入

执行函数的次数num;这个时候传入之后会使用很多的判断执行相关的函数,很多时候我们都会遇到用if-else来进行大量判断的情况

根据funName来执行函数

听了公司前辈的定义,这个涉及到了函数指针和STL的Map的使用

例子可以如下:

#include "stdafx.h"
//#include "person.h"
#include <iostream>
#include "string"
#include "map"
using namespace std;

class test
{
public :
void fun1() { cout<<"call test::fun1"<<endl; }
void fun2() { cout<<"call test::fun2"<<endl; }
void fun3() { cout<<"call test::fun3"<<endl; }

test()
{
m_mapFun["test::fun1"] = &test::fun1;
m_mapFun["test::fun2"] = &test::fun2;
m_mapFun["test::fun3"] = &test::fun3;
}

void call(string strfun)
{
if (m_mapFun.find(strfun) == m_mapFun.end())
cout<<"no function : "<<strfun<<endl;
else
(this->*m_mapFun[strfun])();
}

protected :
typedef void (test::*mfun)();
map<string, mfun> m_mapFun;
};

int _tmain(int argc, _TCHAR* argv[])
{
//Person person1;
test t;
t.call("test::fun1");
t.call("test::fun2");
t.call("test::fun3");
t.call("test::fun4");
return 0;
}
运行结果如下:



函数的执行次数传入还在研究中,主要用于测试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: