1 首先://注意在C和C++里不同
1.1 在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;
1.2 在c++里很簡單,直接
struct Student
{
int a;
};
於是就定義了結構體類型Student,聲明變量時直接Student stu2;
2.其次:
在c++中如果用typedef的話,又會造成區別:
struct Student
{
int a;
}stu1;//stu1是一個變量
typedef struct Student2
{
int a;
}stu2;//stu2是一個結構體類型=struct Student
- 使用時可以直接訪問 stu1.a
- 但是stu2則必須先 stu2 s2;
- 然后 s2.a=10;