【C++】学习笔记[五]

这篇博客详细介绍了C++中的结构体,包括基本概念、定义与使用、结构体数组、结构体指针、嵌套结构体、结构体作为函数参数以及const在结构体中的应用。还通过两个实例,一个是模拟学校老师与学生的关系,另一个是用结构体数组实现英雄排序,阐述了结构体的实际运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、结构体

(一)结构体的基本概念

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

(二)结构体的定义和使用

练习代码如下:

#include <iostream>
#include <string>
using namespace std;

//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student
{
   
	string name;//姓名
	int age;//年龄
	int score;//分数
};


int main()
{
   
	//通过学生类型创建出具体学生
	//第一种方式:
	struct Student s1;
	s1.name = "zhangsan";
	s1.age = 18;
	s1.score = 100;

	cout << "姓名: " << s1.name << endl;
	cout << "年龄: " << s1.age << endl;
	cout << "分数: " << s1.score << endl;
	return 0;
}

在这里插入图片描述

#include <iostream>
#include <string>
using namespace std;

//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student//struct关键字不可以省略
{
   
	string name;//姓名
	int age;//年龄
	int score;//分数
};

int main()
{
   
	//第二种定义方式:
	struct Student s2 = {
    "lisi",20,98 };//struct关键字可以省略
	cout << "姓名: " << s2.name << endl;
	cout << "年龄: " << s2.age << endl;
	cout << "分数: " << s2.score << endl;
	return 0;
}

在这里插入图片描述

#include <iostream>
#include <string>
using namespace std;

//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student
{
   
	string name;//姓名
	int age;//年龄
	int score;//分数
}s3;

int main()
{
   
	//第三种定义方式
	s3.name = "wangwu";
	s3.age = 21;
	s3.score = 67;

	cout << "姓名: " << s3.name << endl;
	cout << "年龄: " << s3.age << endl;
	cout << "分数: " << s3.score << endl;
	return 0;
}

在这里插入图片描述
注意:

  • 定义结构体时struct关键字不可以省略
  • 创建结构体变量时struct关键字可以省略
  • 通过.的方式访问结构体的成员变量

(三)结构体数组

作用:将自定义的结构体放入到数组中方便维护

语法:

struct 结构体名 数组名[元素个数] = 
{
   {
   },{
   },...,{
   }}

练习代码如下:

#include <iostream>
#include <string>
using namespace std;

//创建学生数据类型
//自定义数据类型:一些内置类型集合组成的一个类型
struct Student
{
   
	string name;//姓名
	int age;//年龄
	int score;//分数
};

int main()
{
   
	//创建结构体数组,并对数组元素赋值
	struct Student stuarr[3
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值