基于typedef的⽤法详解
也许新⼿⽤这个关键字不多,但它却是⼀个很有⽤的关键字,可以使代码模块化程度更好(即与其它代码的关联较少),在C++中还是实现Traits技术的基础,也是模板编程的基本语法之⼀。
若说变量定义是为变量命名,⽽typedef(或称为类型定义)就是为类型命名。既然都是命名,那就会有很多类似的地⽅。⽽变量定义我想⼤家都会使⽤,因此类型定义也必然会使⽤。
类型定义的语法可以归结为⼀句话:只要在变量定义前⾯加上typedef,就成了类型定义。这⼉的原本应该是变量的东西,就成为了类型。
int integer; //整型变量int *pointer; //整型指针变量int array [5]; //整型数组变量
int *p_array [5]; //整型指针的数组的变量
int (*array_pointer) [5];//整型数组的指针的变量
int function (int param);//函数定义,也可将函数名看作函数的变量int *function (int param);//仍然是函数,但返回值是整型指针int (*function) (int param);//现在就是指向函数的指针了typedef int integer_t; //整型类型typedef int *pointer_t; //整型指针类型typedef int array_t [5]; //整型数组类型
typedef int *p_array_t [5]; //整型指针的数组的类型
typedef int (*array_pointer_t) [5]; //整型数组的指针的类型typedef int function_t (int param); //函数类型typedef int *function_t (int param); //函数类型
typedef int (*function_t) (int param); //指向函数的指针的类型
上⾯的函数类型在C中可能会出错,因为C中并没有函数类型,它的函数变量会⾃动退化成函数指针;在C++中好像是可以的。在这⾥主要说明的是形式上的相似性.
typedef 类型 定义名;
在编程中使⽤typedef⽬的⼀般有两个,⼀个是给变量⼀个易记且意义明确的新名字,另⼀个是简化⼀些⽐较复杂的类型声明。
其实,在C语⾔中声明变量的时候,有个存储类型指⽰符(storage-class-specifier),它包括我们熟悉的extern、static、auto、register。在不指定存储类型指⽰符的时候,编译器会根据约定⾃动取缺省值。另外,存储类型指⽰符的位置也是任意的(但要求在变量名和指针*之前),也就是说以下⼏⾏代码是等价的:static const int i;const static int i;int const static i;const int static i;
根据C语⾔规范,!所以,我们把上述使⽤static的地⽅替换为typedef:typedef const int i;const typedef int i;int const typedef i;const int typedef i;
上述代码的语义是:将i定义为⼀个类型名,其等价的类型为const int。以后如果我们有i a代码,就等价于const int a。对于有指针的地⽅也是⼀样的,⽐如:
int const typedef *t;那么代码t p。就相当于int const *p。
1)、定义⼀个有10个指针的数组,该指针指向⼀个函数,该函数有⼀个整形参数,并返回⼀个整型?第⼀种⽅法:int (*a[10])(int);
第⼆种⽅法:typedef int (*pfunc)(int); pfunc a[10];
2)、定义⼀个有10个指针的数组,该指针指向⼀个函数,该函数有⼀个函数指针(不带参数,返回值为空)参数,并返回空。
第⼀种⽅法:void (*a[10])(void (*)(void));
第⼆种⽅法:typedef void (*pfuncParam)(void); typedef void (*pfunc)(pfuncParam);pfunc a[10];
3)、⼀个指向有10个函数指针(不带参数,返回值为double)数组的指针第⼀种⽅法:double (*)(void) (*p)[10];
第⼆种⽅法:typedef double (*pfunc)(void); typedef pfunc (*pfuncParam)[10];
pfuncParam p;
⼀、⼀般形式,定义已有类型的别名 typedef 类型 定义名;⼆、创建⼀个新的类型
typedef 返回值类型 新类型名(参数列表);