typedef与struct及指针(C与C++用法异同)

语法:

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;

 

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值