您的位置:首页 > 编程语言 > C语言/C++

结构体定义 typedef struct 用法

2015-11-07 15:48 232 查看
typedef是类型定义的意思。typedef struct 是为了使用这个结构体方便。

具体区别在于:
   若struct
node{ }这样来定义结构体的话。在定义 node 的结构体变量时,需要这样写:struct node n;
若用typedef,可以这样写:typedef struct node{}NODE; 。在申请变量时就可以这样写:NODE n;其实就相当于 NODE 是node 的别名。区别就在于使用时,是否可以省去struct这个关键字。

1 首先:
在C中定义一个结构体类型时如果要用typedef:
typedef struct Student
{
   int
no;
   char
name[12];
}Stu,student;
于是在声明变量的时候就可:Stu stu1;或者:student stu2;(Stu 和student 同时为Student的别名)
如果没有typedef即:
struct Student
{
   int
no;
   char
name[12];
}Stu;
就必须用struct Student stu1;或者struct Stu stu1;来声明
另外这里也可以不写Student(于是也不能struct Student stu1;了)
typedef struct
{
   int
no;
   char
name[12];
}Stu;

2其次:
在c++中如果用typedef的话,又会造成区别:
struct Student
{
   int
no;
   char
name[12];
}stu1;//stu1是一个变量

typedef struct Student2
{
   int
no;
   char
name[12];
}stu2;//stu2是一个结构体类型,即stu2是Student2的别名
使用时可以直接访问stu1.no
但是stu2则必须先定义 stu2 s2;
然后 s2.no=10;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 语法