【C++】结构体

  • 自定义的数据类型,允许存储不同数据类型

定义及使用

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

// 结构体类型定义
	struct student
	{
		//成员列表(属性)

		//姓名
		string name;

		//年龄
		int age;

		//分数
		int score;
	}stu3;

int main()
{
	// .索引赋值
	struct student stu1;
	stu1.name = "张三";
	stu1.age = 20;
	stu1.score = 60;
	cout << "姓名" << stu1.name << endl << "年龄" << stu1.age << endl << "成绩" << stu1.score << endl;

	// 直接对应赋值
	struct student stu2 = {"李四",20,56};

	// 定义时创建后赋值
	stu3.name = "王五";
	stu3.age = 20;
	stu3.score = 78;
	cout << "姓名" << stu3.name << endl << "年龄" << stu3.age << endl << "成绩" << stu3.score << endl;

	return 0;
}

结构体数组

//结构体数组定义
	struct  studentgroup
	{
		string name1;
		int age1;
		int score1;
	};
//结构体数组
int main()
{
	struct studentgroup arry[3] = 
	{
		{"张三",20,60},
	    {"李四",20,56},
	    {"王五",20,78}
	};

	arry[2].name1 = "赵六";  //点索引

	for(int i = 0;i<3;i++)
	{
		cout << "姓名" << arry[i].name1 << endl << "年龄" << arry[i].age1 << endl << "成绩" << arry[i].score1 << endl;
	}
	return 0;
}

结构体指针

  • **->**访问结构体
// 指针访问结构体
	struct student* p = &stu1;
	cout << "姓名" << p->name << endl << "年龄" << p->age << endl << "成绩" << p->score << endl;

结构体嵌套

例:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体

//定义
struct teacher
	{
		int id;
		string name;
		struct student stu;
	};

结构体与函数

值传递

传入结构体值

void printstudent1(struct student stu)
	{
		cout << "姓名" << stu.name << endl << "年龄" << stu.age << endl << "成绩" << stu.score << endl;
	}

地址传递

传入结构体地址,使用指针访问

void printstudent2(struct student* p)
	{
		cout << "姓名" << p->name << endl << "年龄" << p->age << endl << "成绩" << p->score << endl;
	}

结构体中的const

void printstudent2(const struct student* p)限定结构体内存为常量

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值