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


今天的做自动化测试框架的时候发现需要向一个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;
}

运行结果如下:

函数的执行次数传入还在研究中,主要用于测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值