结构体
结构体是用户自定义的数据类型,允许用户存储不同的数据类型。
1、创建学生数据类型
语法 struct 类型名称{成员列表}
2、通过学生类型创建具体学生。
c++中创建变量可以省略struct
2.1 struct student s1; //先定义再通过.访问结构体变量中的属性。
s1.name=“李四”;
s1.age=18;
s1.score=100;
2.2 struct student s2={“李四”,19,80};
2.3在定义结构体时顺便创建结构体变量
struct student
{成员列表}s3;
3、结构体指针
struct student
{
string name;
int age;
int score;
};
struct student s={"张三",18,100};
struct student *p=&s;//通过指针指向结构体变量
p->name;//通过指针访问结构体变量中的数据。
//结构体指针可以通过->访问结构体变量
4、结构体嵌套结构体
在结构体中可以定义另一个结构体作为成员,用来解决实际问题。
5、结构体中使用const
作用:用const来防止函数误操作。