struct与typedef struct的区别
在C中定义一个结构体类型
- 若使用typedef如下:
typedef struct Student
{
int a;
}Stu; //这里的Stu实际上就是struct Student的别名。
则在声明变量时可以直接:Stu stu1;
- 若没有使用typedef
则声明变量时必须用:struct Student stu1;
在c++中定义一个结构体类型
可以不使用typedef,如下:
struct Student
{
int a;
};
声明变量时直接:Student stu2;
在c++中如果用typedef的话,又会造成以下区别:
typedef struct Student2
{
int a;
}stu2; //stu2是一个结构体类型
struct Student
{
int a;
}stu1; //stu1是一个变量
使用时可以直接访问stu1.a //当成成员函数的调用
但是stu2则必须先 stu2 s2;
然后 s2.a=10;
总结:在c++中可以不需要typedef就可以Student stu2是因为在c++中struct也是一种类,可以直接使用Student stu2来定义一个Student的对象,但c中去不可以