函数指针
来源:互联网 发布:淘宝号注册马上注册 编辑:程序博客网 时间:2024/05/17 23:14
和其他简单变量一样,编译阶段会给函数代码块分配一块内存,内存的首地址其实就是函数的名字,通常也称作指向函数的指针,即函数指针。
如下 :
int max(int a,int b){int result = a > b ? a : b;cout<<result<<endl;}这个函数返回a , b两数的最大者,我们可以为定义一个指向这个函数的指针fun:
int (*fun)(int,int); ①
那么,我们说fun的类型是 int ( * ) (int ,int ) ,就和我们说 int age = 0 , age 的 类型是int一样,再来看看 ① 出的代码是个什么意思:
## 它表示fun指向一个返回值是 int ,参数为两个 int 值得函数。##
注意,不能写成 int * fun ( int , int ) ,因为()的优先级比* 高 ,int * fun ( int , int ) 表示 参数为两个 int 类型的fun函数 返回一个指向 int 的指针。
以下是两个例子 :
例子 1 :
#include<iostream>using namespace std;int max(int a,int b){int result = a > b ? a : b;cout<<result<<endl;}int main(){//定义fun为 int (*)(int,int) 类型的函数指针。 int (*fun)(int,int);fun = max;(*fun)(23,56);(*fun)(100,78);return 0;}
结果 :
例子 2 :
#include<iostream>using namespace std;typedef struct App{void *userData;}App;/****void (*)() :表示返回值是void,参数也是void(无参数)的函数 . **/// 将 void (*)() 类型用typedef 定义为 FUNTYPE类型. typedef void(* FUNTYPE)();void callFunction(App *app){/** 将void * 的userData强转成FUNTYPE类型,即 void (*)()类型.*并执行这个函数. */(*((FUNTYPE)(app->userData)))();}void hello(){cout<<"Hello world!"<<endl;}int main(){App *app=new App;//将 void (*)() 类型的地址转换成 void * app->userData=(void *)hello;callFunction(app);delete app;return 0;}
结果 :
0 0
- 指针函数 函数指针
- 函数指针/指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 指针函数,函数指针
- 函数指针,指针函数,
- 指针函数,函数指针
- 函数指针 指针函数
- 函数指针、指针函数
- 指针函数&函数指针
- 函数指针 指针函数
- 函数指针 指针函数
- 函数指针&指针函数
- 指针函数 函数指针
- 指针函数 &函数指针
- 函数指针&指针函数
- void指针 函数指针
- pcap文件分析-上之wireshark工具使用
- python标准输入输出
- Android自定义View实现开关效果
- poi基本导入
- POJ 1733 Parity game
- 函数指针
- Spark DataFrames
- 坑爹的 小数加法
- 异或的应用及性质
- SmartMonkey--UI遍历
- oracle_单引号问题和execute immediate 赋值问题
- 洛谷 P1018 [NOIP2000 T2] 乘积最大
- 【华为OJ17】坐标移动----方法二(推荐)
- Unity资源热更之AssetBundle(3)———新版本AssetBundle