1 在C和C++里的不同
在c中定义一个结构体类型用typedef:
typedef struct Student
{
int m;
}Stu;
用这种形式定义的时候,在声明结构体变量的时候可用:Stu stu1; 这种形式也等同于struct Strdent stu1;
这里的Stu和struct Student等同,Stu也就相当于struct Student的另一个名字。
浮点数在定义的时候也可以加上Student,如下面这种形式:
typedef struct
{
int m;
}Stu;d
但是在c++中就很简单,如下面这种形式:
struct Student
{
int m
};
在定义结构体变量的时候直接用下面这种形式:Student stu
2. 使用typedef 和不适用 typedef 时,stu1是有区别的,如下面所示:
struct Student
{
int a;
}stu1; //stu1是一个变量 也可以这样定义 Student stu1;
typedef struct Student2
{
int a;
}stu2; //stu是一个结构体类型的名字而不是结构体类型的变量
3 如果在c程序中我们写:
typedef struct
{
int num;
int age;
}stu1,stu2,stu3;
这是什么意思呢?这相当于
typedef struct
{
int num;
int age;
}stu1;
typedef stu1 stu2;
typedef stu1 stu3;
也就是说stu1,stu2,stu3三者都是结构体类型。声明变量时用任何一个都可以,在c++中也是如此。但是你要注意的是这个在c++中如果写掉了typedef关键字,那么stu1,stu2,stu3就变成三个不同的结构体变量了。
4 typedef struct和struct的区别:
typedef struct Student
{
int a;
long b;
}Stu;
上面的Student是标识符,Stu是变量类型(相当于(int,char等))。
这语句实际上完成两个操作:
1) 定义一个新的结构类型
struct Student
{
int a;
long b;
};
2) typedef为这个新的结构起了一个名字,叫Stu。
因此,Stu实际上相当于struct Student,我们可以使用Stu stu1这种形式来定义结构体变量。