c++ day 4 结构体定义,结构体数组

这篇博客介绍了C++中结构体的定义与使用,包括如何创建自定义的学生数据类型,以及通过结构体创建具体的学生实例。同时,讲解了结构体数组的创建和遍历,展示了如何初始化和单独赋值给结构体数组元素。示例代码中包含了结构体的声明、实例化以及遍历结构体数组的过程。
摘要由CSDN通过智能技术生成

用户自定义的数据类型

结构体定义 :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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值