typedef struct 和 struct在C和C++的区别
在C++中,下列程序可以直接编译通过,即Student1
、Student2
、TYPEDEF_STU2
都相当于一种类型。
#include <stdio.h>
struct Student1 {
int id;
char* name;
};
typedef struct Student2 {
int id;
char* name;
}TYPEDEF_STU2;
int main() {
Student1 stu1;
stu1.id = 1;
stu1.name = "Jack";
printf("id == %d, name == %s\n", stu1.id, stu1.name);
Student2 stu2;
stu2.id = 2;
stu2.name = "Rose";
printf("id == %d, name == %s\n", stu2.id, stu2.name);
TYPEDEF_STU2 stu3;
stu3.id = 3;
stu3.name = "Tony";
printf("id == %d, name == %s\n", stu3.id, stu3.name);
return 0;
}
但是在C语言中,struct Student1
、struct Student2
、TYPEDEF_STU2
才算一个新类型,即使用typedef关键字时,可以在定义结构体新变量时少些一个struct
关键字。
#include <stdio.h>
struct Student1 {
int id;
char* name;
};
typedef struct Student2 {
int id;
char* name;
}TYPEDEF_STU2;
int main() {
struct Student1 stu1; // 需要添加student
stu1.id = 1;
stu1.name = "Jack";
printf("id == %d, name == %s\n", stu1.id, stu1.name);
struct Student2 stu2; // 需要添加student
stu2.id = 2;
stu2.name = "Rose";
printf("id == %d, name == %s\n", stu2.id, stu2.name);
TYPEDEF_STU2 stu3;
stu3.id = 3;
stu3.name = "Tony";
printf("id == %d, name == %s\n", stu3.id, stu3.name);
return 0;
}