C++ 函数指针

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int PrintVal(int i){
 5     cout<<i<<endl;
 6     return 0;
 7 }
 8 
 9 int Add(int i,int j){
10     return i+j;
11 }
12 
13 void Compare(int i,int j){
14     if(i==j)
15         cout<<i<<"=="<<j<<endl;
16     else if(i>j)
17         cout<<i<<">"<<j<<endl;
18     else
19         cout<<i<<"<"<<j<<endl;
20 }
21 typedef int(*pFunc)(int);
22 
23 int main(){
24     pFunc p1 = PrintVal;
25     int (*p2)(int,int);
26     p1(7);
27     p1 = &PrintVal;
28     (*p1)(8);
29     p2 = Add;
30     cout<<p2(4,5)<<endl;
31 
32     p2 = reinterpret_cast<int(*)(int,int)>(Compare);//进行强转
33 
34     p2(4,5);
35 }

1、书写方式 type (*name)(param);

2、函数指针书写比较复杂,一般使用typedef来简化。

3、函数原型必须与定义函数指针时的原型一致,否则会导致编译错误。但是,在某些特殊情况下,可以使用reinterpret_cast运算在不同类型的函数指针间进行转换。

4、有一种函数叫做“回调函数”。回调函数是一个定义了函数的原型,函数体则交由第三方来实现的一种动态应用模式。在实现函数调用时,先将回调函数的地址作为参数之一传递给主调函数。在主调函数内部通过函数指针调用回调函数。回调函数的机制打破了主调函数与被掉函数静态绑定的限制,为用户提供一种充分利用操作系统的方便手段。

原文地址:https://www.cnblogs.com/teng-IT/p/6015251.html