语法:
typedef 类型名称 类型标识符
【一】
引例,帮助理解:
typedef int zhengshu;
zhengshu a=12,b[20]={2,0,3};
将int类型取别名zhengshu。zhengshu a=12等价于int a=12。
【二】
例1 在C中的应用
typedef struct node{
int data;
char l[20],r[20];
}tree;
申明结构体struce node的别名为tree。
于是可以这样:
tree A;
申明结构体类型变量A。它的效果等价于
struce node A;
因为struct node的别名就是tree。
例2 在C++中的应用
struct node{
int data;
char l[20],r[20];
};
这里,在struct前面不需要加typedef,如果加了编译时会提示:
[Warning] 'typedef' was ignored in this declaration [enabled by default]
这里,node就是一个用户自定义的数据类型,与int一样。申明node类型的变量A如下:
node A;
也可以写成:
struct node A;
【三】
例3 加入指针,在C中的应用
typedef struct AVLNode * Position;/*定义结构体指针别名为Position*/
typedef Position AVLTree;/*定义Position别名为AVLTree*/
typedef struct AVLNode{
int Data;
AVLTree Left;
AVLTree Right;
};
另一种写法:
typedef struct AVLNode{
int Data;
struct AVLNode * Left;
struct AVLNode * Right;
};
typedef struct AVLNode * Position;
typedef Position AVLTree;
例4 加入指针,在C++中的应用
typedef struct AVLNode * Position;/*定义结构体指针别名为Position*/
typedef Position AVLTree;/*定义Position别名为AVLTree*/
struct AVLNode{
int Data;
AVLTree Left;
AVLTree Right;
};
与例3前半部分的区别在于在结构体前面不用写typedef。
对应的另一种写法:
struct AVLNode{
int Data;
AVLNode * Left;
AVLNode * Right;
};
typedef struct AVLNode * Position;
typedef Position AVLTree;
与例3后半部分的区别之一在于在结构体前面不用写typedef,之二在于结构体内申明左右儿子时不用写struct。
【四】
最后说一点,
typedef struct AVLNode * Position;
typedef Position AVLTree;
可以写成:
typedef struct AVLNode * AVLTree;