”typedef是用来定义类型的“,多么简单的解释,可我就是败在这句话上,走了很多弯路。
看别人(俄罗斯的大牛)的程序时碰到了这个情况:
typedef FILTER_ACTION FILTER_BUFFER(............);
这里FILTER_ACTION是一个枚举类型,下文出现了这样的引用:
FILTER_BUFFER *filter_client;
FILTER_BUFFER *filter_server;
明显上句typedef是定义了一个函数类型FILTER_BUFFER,而函数类型是用来定义函数的,而不能直接实现的(询问了别人,都说找FITER_BUFFER函数的具体实现)。下文定义了两个只想该函数类型的变量,要想让这两个变量能指向某个具体的函数,需要为其赋值,然后寻找赋值的函数的实现。
可能这样讲不是很明白,上代码:
#include <stdio.h>
typedef void test(char *str);
typedef void (*test2)(char *str);
void print(char *string);
void main(void)
{
//这是函数指针的变种,不常见
test *first;
test *second;
//这种形式比较常见,函数指针
test2 first_test2;
test2 second_test2;
//关键在于赋值,它使得指针指向了具体的函数
first = print;
second = print;
first_test2 = print;
second_test2 = print;
//利用指针调用函数
first("first");
second("second");
first_test2("first_test2");
second_test2("second_test2");
}
void print(char *string)
{
printf("%s\n",string);
}
输出结果是:
first
second
first_test2
second_test2
这种形式使得程序很灵活,函数的定义和实现相分离,修改起来容易!