typedef 修饰 struct ,因为在C和C++中struct中意义不完全一样,所以我们分两块姜,在C中typedef修饰struct和C++中typedef修饰struct。
一:C中typedef修饰struct
在C中定义一个结构体类型要用typedef:
typedef struct Student
{
int a;
}Stu;
于是在声明变量的时候就可:Stu stu1;(如果没有typedef就必须用struct Student stu1;来声明)这里的Stu实际上就是struct Student的别名。Stu==struct Student。另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是Stu stu1;)
typedef struct
{
int a;
}Stu;
应用实例代码:
#include <stdio.h>
struct Student
{
int id;
};
typedef struct Teacher
{
char *subject;
}T;
int main()
{
struct Student stu1;
stu1.id = 1;
printf("%d\n",stu1.id);
T t1;
t1.subject = "math";
printf("%s\n",t1.subject);
return 0;
}
二:C++中typedef修饰struct
因为在C++是面向对象的语言,所以C++中有类的概念,而struct在默认情况下就约等于class了。只是有一些小小的区别,就是成员默认的访问级别是公有的,而class默认私有的。
回归正题。C++中typedef修饰struct的时候会出现如下情况。
struct Student
{
int a;
}stu1;//stu1是一个变量
typedef struct Student2
{
int a;
}stu2;//stu2是一个结构体类型=struct Student
使用时可以直接访问stu1.a
但是stu2则必须先 stu2 s2;
然后 s2.a=10;