用户自定义的数据类型
结构体定义 :struct 结构体名 {结构体成员列表}
结构体变量创建:(这里的struct可以省略)
1.struct 结构体名 变量名
2.struct 结构体名 变量名 = {成员1值,成员2值}
3.定义结构体时顺便创建变量
例子,(1)创建学生数据类型(姓名,年龄,分数)
sturct student //可理解为一个子函数
{
string name;
int age;
int score;
}s3; //顺便创建变量
(2)通过学生类型创建具体学生
1.struct 结构体名 变量名
struct student s1;
s1.name = "张三"; //给s1属性赋值,通过 . 访问结构体变量中的属性
s1.age = 16;
s1.score = 13;
2.struct 结构体名 变量名 = {成员1值,成员2值}
struct student s1 = {"赵大",14,67};
3.定义结构体时顺便创建变量
s3在结构体后面
s3.name = "张水电费"; //给s1属性赋值,通过 . 访问结构体变量中的属性
s3.age = 19;
s3.score = 153;
struct student
{
string name;
int age;
int score;
}s3;
int main()
{
struct student s1;
s1.name = "唐颐和";
s1.age = 15;
s1.score = 56;
cout << s1.name << s1.age << s1.score << endl;
struct student s2 = { "丽莎",18,78 };
cout << s2.name << s2.age << s2.score << endl;
s3.name = "阿刁和";
s3.age = 115;
s3.score = 546;
cout << s3.name << s3.age << s3.score << endl;
system("pause");
return 0;
}
2,结构体数组
struct 结构体名 数组名[元素个数] = {{},{},.......}
1.定义结构体
sturct student
{
string name;
int age;
int score;
}
2,创造结构体数组
struct student stuarry[3] = //还是个一维数组,里面是根据结构体赋值
{
{"张",19,67}, //这里是直接给所有赋值
{"李",15,97}, //数组是加逗号
{"王",17,53}
}
3.也可以单独每个赋值
stuarry[2].name = "李";
stuarry[2].age = 18;
stuarry[2].score = 66;
4.遍历结构体数组
for(i=0;i<3;i++)
{
cout << stuarry[i].name << ;
}
完整代码
struct student
{
string name;
int age;
int score;
}s3;
int main()
{
struct student stuarry[3] = //这里定义的是数组里数的总个数,所有定义的书的个数必
须小于等于这个值
{ //这里直接赋值的有两个,下面再定义的有一个,所以为3
{"张",16,66},
{"李",16,35},
};
stuarry[2].name = "阿萨德"; //如果这里不赋值,输出的结果为00,字符为空
stuarry[2].age = 33;
stuarry[2].score = 89;
for (int i = 0; i < 3; i++)
{
cout << stuarry[i].name << stuarry[i].age << stuarry[i].score << endl;
}
system("pause");
return 0;
}