c++容器(vector|map)中使用函数指针


我要动态生成mfc菜单,动态绑定响应命令。
首先把菜单关键词和函数指针绑定在map中,
再通过关键词找到函数来执行。
#include  " stdafx.h "

#include <vector>
#include <map>
#include < string>

using  namespace std;

//  声明一个函数指针
int(*pFunc)( int);
int func1( int nIn){ return nIn +  1;}
int func2( int nIn){ return nIn +  20;}

typedef  int(*pInt)( int); // 定义别名才能放在vector中

void main()
{
    pFunc = func1; //  把函数名赋给函数指针
     int n = pFunc( 1);
    pFunc = &func2;
    n = pFunc( 1);
     // vector<int(*pFun)(int)> v_pFunc; // 不能这样定义
    
//
    vector<pInt> v_pInt;
    v_pInt.push_back(func1);
    v_pInt.push_back(func2);
     int i = v_pInt[ 0]( 2);
    i = v_pInt[ 1]( 2);
     //
    map< string,pInt> map_pInt;
    map_pInt.insert(pair< string,pInt>( " key1 ",func1));
    map_pInt.insert(pair< string,pInt>( " key2 ",func2));
     int j = map_pInt[ " key1 "]( 3);
    j = map_pInt[ " key2 "]( 3);
}
20121028更正vector可以直接放函数指针类型,没理解到位。
// vector只能放类型,不能放函数指针变量名
vector< int(*)( int)> v_pFunc;
v_pFunc.push_back(func1);
v_pFunc.push_back(func2);
int k = v_pFunc[ 0]( 5);
k = v_pFunc[ 1]( 5);
url: http://greatverve.cnblogs.com/archive/2012/10/27/vector-ptr.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM