函数指针和typedef
来源:互联网 发布:synthesia piano mac 编辑:程序博客网 时间:2024/05/23 15:24
昨天在读一个SDK的sample,看到一句特别奇怪的用了typedef(C++ Primer P60)的语句。看了很久,查了资料才知道是做什么的。
typedef void (*PFuncOnTouchGesture)(const TouchGesture & tg,void * call_object);
问了大神之后,给我发了wikipedia的链接,看了一下属于 Using typedef with function pointers这一种用法,就是给函数指针重新命名的意思吧。
函数指针(C++ Primer P221)的定义也不是很清楚,
函数指针指向的是函数而非对象。函数的类型,是由返回类型和形参类型共同决定的,要想定义一个指向特定类型的函数的函数指针,就用指针替换函数名即可。
看这一句语句,函数指针是 void (*PFuncOnTouchGesture)(const TouchGesture &tg,void *call_object); 就是指向一个返回类型为void,形参类型为const TouchGesture &tg,void *call_object的函数。
下面代码是没有使用typedef来定义函数指针的类型别名的情况:
int do_math(float arg1, int arg2) { return arg2;}int call_a_func(int (*call_this)(float, int)) { int output = call_this(5.5, 7); return output;}int final_result = call_a_func(&do_math);
This code can be rewritten with a typedef as follows:
typedef int (*MathFunc)(float, int);int do_math(float arg1, int arg2) { return arg2;}int call_a_func(MathFunc call_this) { int output = call_this(5.5, 7); return output;}int final_result = call_a_func(&do_math);
Here, MathFunc is the new alias for the type. A MathFunc is a pointer to a function that returns an integer and takes as arguments a float followed by an integer.
When a function returns a function pointer, it can be even more confusing without typedef. The following is the function prototype ofsignal(3) from FreeBSD:
void (*signal(int sig, void (*func)(int)))(int);
The function declaration above is cryptic as it does not clearly show what the function accepts as arguments, or the type that it returns. A novice programmer may even assume that the function accepts a singleint as its argument and returns nothing, but in reality it also needs a function pointer and returns another function pointer. It can be written more cleanly:
typedef void (*sighandler_t)(int);sighandler_t signal(int sig, sighandler_t func);
再回到这里
typedef void (*PFuncOnTouchGesture)(const TouchGesture & tg,void * call_object);PFuncOntouchGesture就是一个 指向某种特定类型的函数的指针的别名,实际就是一种类型的别名。这种类型代表了一类的指向函数的指针。有点绕来绕去了。
- typedef和函数指针
- typedef 和 函数指针
- 函数指针和typedef
- 函数指针和typedef
- typedef函数指针和函数指针用法
- 关于函数指针和typedef
- 关于函数指针和typedef
- 关于typedef和函数指针
- 函数指针定义和typedef
- typedef函数指针类型和函数类型
- typedef 和指向函数的指针
- 函数指针和typedef的应用
- typedef定义函数指针和block
- 26.函数指针实战和typedef
- typedef 和 函数指针 的使用
- 25.数组指针和函数指针及typedef
- 全局函数指针数组typedef和成员函数指针数组类内外部typedef
- 函数指针与typedef
- keil .sct 文件的理解
- cura-engine学习(2)
- 数据和表
- 前台接收json
- java 读取excel 2007 .xlsx文件
- 函数指针和typedef
- Android studio 查看应用MD5和SHA1值(应用签名)
- Python变量、字符串
- 项目代码管理
- React Native环境配置(Windows)
- dubbox为dubbo提供REST服务(dubbox + springmvc)
- pycharm 2016.2注册码
- C#判断是不是回文
- Mac安装Protobuf