什么是结构体?
之前的学习中我们知道了数组是一个容器,而且是存放固定大小数据的容器,而且存放的元素的数据类型必须要一致。
比如数据库中有这样的一条记录学号 性别 年龄 成绩 地址应该怎样存放
结构体:在一个组合项目中包含若干个类型不同的数据项,c++允许自己指定这样一种数据类型,称为结构体。(用户自定义一种新的数据类型,这种想法是面向对象思想的开端)
struct Student{
int num;
char name[20];
char sex;
int age;
float score;
char address[30];
}
上边的定义称为结构体类型
每一个成员称为结构体中的一个域(field),成员表又叫域表。
下边进行结构体的初始化
3种方法:
(1)先声明结构体再定义结构体变量
struct Student{
int num;
char name[20];
char sex;
int age;
float score;
char address[30];
};
Student student1,student2;
(2) 在声明类型的同时定义变量
struct Student{
int num;
char name[20];
char sex;
int age;
float score;
char address[30];
} student1, student2;
(3)结构体成员也可以是一个结构体
struct Date{
int month;
int day;
int year;
};
struct Student{
int num;
string name;
char sex;
int age;
Date birthday;
string addr;
}student1,student2;
下边对结构体进行初始化:
struct Student{
int num;
string name;
char sex;
int age;
float score;
string addr;
}student1={10001,"zhang xin",'M',19,90.5,"shanghai" };
Student student1={10002,"wangli",'F',20,98,"beijing" };
结构体3步:声明 定义 初始化
C++结构体详解:声明、定义与初始化
本文介绍了C++中的结构体,作为数据类型的扩展,结构体允许组合不同类型的元素。通过示例展示了如何声明、定义和初始化结构体,包括单独声明和定义、同时声明和定义,以及结构体成员为其他结构体的情况。最后,文章提供了两种结构体初始化的方式。
6966

被折叠的 条评论
为什么被折叠?



