现在的位置: 首页 > 综合 > 正文

函数指针及map运用

2013年08月06日 ⁄ 综合 ⁄ 共 781字 ⁄ 字号 评论关闭

最近遇到需要写一个类似于Qt connect的函数,上网查没查到map存放类成员函数指针的调用,看到别人对类成员函数指针的使用,偶来感觉,得瑟一下。

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <map>
#include <string>
using namespace std;
class A
{
public:
 void A_test()
 {
  printf("A_test\n");
 }
 void A2_test()
 {
  printf("A2_test\n");
 }
};
typedef void(*fun)();
typedef void(A::*funA)();
void print()
{
 printf("print\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
 map<std::string,fun> funMap;
 map<std::string,funA> funMapA;
 funMap["print"] = print;
 funMapA["a_test"] = &A::A_test;
 funMapA["a2_test"] = &A::A2_test;
 if (funMap.count("print"))
 {
  funMap["print"]();
 }
 if (funMapA.count("a2_test"))
 {

//funMapA["a2_test"]();此处不能这样调用
  funA fa = funMapA["a2_test"];
  A a;
  (a.*fa)();
 }
 if (funMapA.count("a_test"))
 {
  funA fa = funMapA["a_test"];
  A a;
  (a.*fa)();
 }
 system("pause");
 return 0;
}

抱歉!评论已关闭.