C++学习笔记——结构体

#include <iostream>
#include <string>

using namespace std;
/*结构体属于用户自定义数据类型,允许用户存储不同的数据类型*/
void printstu1(struct Student s);
void printstu2(struct Student *s);
void printstu3(const struct Student *s);
/**************************************************************
*1、定义结构体
*  语法: struct 名称 {   };
**************************************************************/
struct Student
{
	string name;

	int age;

	int score;

}s3;

int main()
{
	/**************************************************************
	*2、创建学生变量,struct可以省略
	**************************************************************/
	//1、
	struct Student s1;
	s1.name = "zhagnsan";
	s1.age = 12;
	s1.score = 99;
	//2、
	struct Student s2 = {"lisi",13,80};
	printstu1(s1);//值传递
	printstu2(&s2);//地址传递
	//3、创建结构体时顺便创建变量,如上

	/**************************************************************
	*3、结构体数组:将自定义的结构体放入到数组中方便维护
	*   语法:struct 结构体名  数组名[元素个数] = {{},{},{}};
	**************************************************************/
	struct Student arr[3] =
	{
		{ "张三",18,80 },
		{ "李四",19,60 },
		{ "王五",19,62 }
	};
	//给结构体里元素赋值
	arr[2].score = 90;
	arr[2].age = 20;
	arr[2].name = "李六";

	//遍历结构体数组
	for (size_t i = 0; i < 3; i++)
	{
		cout << " 姓名 " << arr[i].name
			 << " 年龄 " << arr[i].age
			 << " 分数 " << arr[i].score << endl;
	}
	/**************************************************************
	*4、结构体指针:通过结构体指针访问结构体中成员
	*   利用操作符   ->
	**************************************************************/
	//通过指针指向结构体变量s1,struct 可以省略
	struct Student * p = &s1;

	//通过指针访问结构体中的数据
	cout << " 姓名 " << p->name << endl;

	/**************************************************************
	*5、结构体嵌套结构体
	*   定义该结构体之前要定义嵌套的结构体
	**************************************************************/
	//定义老师结构体
	struct teacher
	{
		int id;
		string name;
		int age;
		struct Student stu;
	};
	teacher t;
	t.age = 25;
	t.stu.name = "zhangsan";

	system("pause");
	return 0;
}

/**************************************************************
*6、结构体做函数参数
*   值传递    地址传递
**************************************************************/

//打印学生信息
//1、值传递,不会改变实参的值
void printstu1(struct Student s)
{
	cout << "子函数中姓名:" << s.name << endl;
}

//2、地址传递,通过地址操作可以改变实参的值,减少内存空间
void printstu2(struct Student *s)
{
	cout << "子函数中姓名:" << s->name << endl;
}
/**************************************************************
*7、const使用场景
* 防止误操作
**************************************************************/
void printstu3(const struct Student *s)
{
	//s->age = 20;(错误,常量指针不可以被修改内容)
	cout << "子函数中姓名:" << s->name << endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值