C++ 函数指针的定义方法及使用

 

int add(int a,int b){
    return a+b;
}

 

第一种,c语言通用。定义一个process_job函数指针类型,返回值为 int ,函数参数为int a,int b。使用用两种方法。

    typedef int (*process_job)(int a,int b);
    process_job a;
    a = add;

   cout << a(10,12) << endl;
    cout << (*a)(10,12) << endl; //OK

第二种,C++。使用,只有一种方法。

#include <functional>
typedef function< int(int,int)> task;
        task t = add;
    cout << t(22,23) << endl;     
       // cout << (*t)(22,23) << endl; error

 

函数指针作为函数参数传递

int add(int a,int b){
    cout << a+b << endl;
    return a+b;
}

void MyFun(int a,int b,int (*p)(int,int)){
    p(a,b);
}

    MyFun(2,3,add);

 

posted @ 2015-08-25 12:08  forxtz  阅读(1267)  评论(0)    收藏  举报