c++之结构体模块

1、结构体的基本概念

概念:用户自定义的数据类型,允许用户存储不同的数据类型

2、结构体定义和使用

语法:struct 结构体名 {结构体成员列表};

struct Student
{
	string name;
	int age;
	int score;

};

通过结构体创建变量的三种形式:

  • struct 结构体名 变量名;
	Student s;
	s.name = "张三";//给变量赋值
	s.age = 19;
	s.score = 80;
  • struct 结构体名 变量名={成员1值,成员2值…};
Student s = { "张三",19,70 };
  • 定义结构体时顺便创建变量
struct Student
{
	string name;
	int age;
	int score;

}s;

在这里插入图片描述

	s.name = "张三";//给变量赋值
	s.age = 19;
	s.score = 80;

3、结构体数组

作用:将自定义的数据类型放到数组中,方便维护
语法:struct 结构体名 数组名[元素个数]={ {},{},{}… {} }
示例:

Student stuArr[3] = { {"张三",19,90},{"李四",18,80},{"王五",20,70} };

4、结构体指针

作用:通过结构体指针访问结构体属性

    Student s = {"张三",20,90};
	Student* stu = &s;
	cout << "姓名:" << stu->name << " " 
		<< "年龄:" << stu->age << " " 
		<< "分数:" << stu->score << endl;

5、结构体嵌套结构体

作用:结构体中的成员可以是另外一个结构体
示例:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体。

struct Student
{
	string name;
	int age;
	int score;

};
struct Teacher
{
	int id;
	string name;
	int age;
	struct Student stu;

};
    Teacher t;
	t.id = 10001;
	t.name = "李四";
	t.age = 50;
	t.stu.name = "李小四";
	t.stu.age = 20;
	t.stu.score = 80;

6、结构体做函数参数

作用:将结构体作为参数向函数中传递

  • 值传递,形参不能更改实参
void printInfo(Teacher t)
{
	cout << "教师号:" << t.id << " "
		<< "教师姓名:" << t.name << " "
		<< "教师年龄:" << t.age << " " << endl
		<< "学生姓名:" << t.stu.name << " "
		<< "学生年龄:" << t.stu.age << " "
		<< "学生分数:" << t.stu.score << endl;
}

在这里插入图片描述

  • 地址传递,形参可以更改实参
void printInfo(Teacher* t)
{
	t->age = 200;
	cout << "教师号:" <<t->id<<" "
		<< "教师姓名:" << t->name << " "
		<< "教师年龄:" << t->age << " " << endl
		<< "学生姓名:" << t->stu.name << " "
		<< "学生年龄:" << t->stu.age << " "
		<< "学生分数:" << t->stu.score << endl;
}

在这里插入图片描述

7、结构体中const的使用

作用:使用const防止误操作,这里使用指针是为了减少内存的消耗。指针只占4个字节,不会对形参数据做出一份拷贝。
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值