函数指针和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就是一个 指向某种特定类型的函数的指针的别名,实际就是一种类型的别名。这种类型代表了一类的指向函数的指针。有点绕来绕去了。


0 0