C++中结构体struct的定义
结构体struct是C++中的一种自定义数据类型,它可以用来把多个不同类型的数据组合成一个整体,它可以用来定义一些特殊的数据结构。结构体struct可以用关键字struct来定义,其语法结构如下:
struct 结构体名
{
成员变量1;
成员变量2;
成员变量3;
...
};
定义结构体struct时,可以在大括号里面定义多个成员变量,每个成员变量可以是任意类型,可以是整型、字符型、浮点型等等,可以是自定义的数据类型,比如另一个结构体struct,也可以是数组等。
C++中结构体struct的使用
定义完结构体struct之后,就可以使用它来定义变量了,使用方法和定义其他类型的变量一样,只是在定义变量时,要把变量类型改为定义的结构体struct类型,如下所示:
struct student
{
char name[20];
int age;
float score;
};
student stu1;
定义完结构体struct类型的变量之后,就可以对它的成员变量进行赋值操作了,比如:
stu1.name = "john"; stu1.age = 20; stu1.score = 95.5;
结构体struct也可以用来定义函数参数,比如:
void printStudent(student stu)
{
printf("name: %s\n", stu.name);
printf("age: %d\n", stu.age);
printf("score: %f\n", stu.score);
}
结构体struct也可以用来定义数组,比如:
student stuArray[10];