C++基础知识篇——结构体

结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

创建结构体

语法:
struct 结构体名 {
结构体成员列表
};
注意分号不要忘记

struct Student {
	string name;
	int height;
	int weight;
}

定义结构体变量

可通过以下几种方式创建结构体类型的变量
1.定义时创建一个变量

struct Student {
	string name;
	int height;
	int weight;
}s1;

2.先定义结构体,后创建结构体变量。创建时可以同时赋值,也可以在之后赋值。

Student s1 = { "wang", 180, 60 };
Student s2;
s2.name = "wang"; s2.height = 180; s2.weight = 60;

结构体数组

在之前创建的结构体Student基础上,可以创建结构体数组,数组每个成员的数据类型都为所创建的结构体类型。
同时,结构体在创建时还可以给定默认的初始值

struct Student {
	string name = "Wu";
	int height = 172;
	int weight;
}int main() {
	//先定义后赋值
	Student array1[2];
	array1[0].name = "wang"; 
	array1[0].height = 180;
	array1[0].weight = 60;
	array1[1].weight = 62//定义的同时赋值
	Student array2[2] = {
		{ "Li", 180, 60 },
		{ "Wu", 172, 62 },
	};
	//遍历输出数组元素,此时array1与array2各元素相同
	for (int i = 0; i<2; i++) {
		cout << "name: " << array1[0].name 
		     << " height: " << array1[0].height 
		     << " weight: " << array1[0].weight
		     << endl;
	}
	return 0;
}

结构体指针

通过结构体指针访问结构体成员
利用操作符 ->
还是上面的例子:

struct Student {
	string name;
	int height;
	int weight;
}int main() {
  	//创建一个结构体变量
	Student s1 = { "wang", 180, 60 }//定义一个结构体指针指向该变量
	Student *p = &s1;
	//访问结构体成员
	cout << "name: " << p->name 
		 << " height: " << p->height 
		 << " weight: " << p->weight
		 << endl;
	return 0;
}

结构体嵌套

在一个结构体内也可以包含另外一个结构体,结构体数组等
如一个教室包含50个学生

struct Student {
	string name;
	int height;
	int weight;
};
struct ClassRoom {
	int id;
	Student array[50];
};
int main() {
	ClassRoom c1;
	c1.id = 1;
	//这里只对第一个学生赋值
	c1.array[0].name = "zhang";
	c1.array[0].height = 182;
	c1.array[0].weight = 60;
	cout << "ClassRoom id: " << c1.id <<endl
	     << "firstStudent name: "   << c1.array[0].name
	     << " height: " << c1.array[0].height
	     << " weight: " << c1.array[0].weight
	     << endl;
	return 0;
}

结果如下:在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值