C++基础 结构体

/*
* B站学习--[64 - ]
* day7 学习成果
*/

/*
 * 8 结构体
 * 
 * 8.1 结构体的基本概念
 * 
 * 结构体属于用户的自定义的数据类型,允许用户存储不同的数据类型
 * 
 * 
 * 8.2 结构体的定义和使用
 * 
 * 语法:struct 结构体名{结构体成员列表};
 * 
 * 通过结构体构建变量的三种方式:
 *		1.struct 结构体名 变量名
 *		2.struct 结构体名 变量名 = {成员1值,成员2值,...};
 *		3.定义结构体时随便创建变量
 * 
 * 
 * 8.3 结构体数组
 * 
 * 将自定义的结构体放入到数组中方便维护
 * 
 * 语法: struct 结构体名 数组名[元素个数] = {{},{},{},...};
 * 
 * 
 * 8.4 结构体指针
 * 
 * 通过指针访问结构体中的成员
 * 
 * 利用操作符 -> 可以通过结构体指针访问结构体属性
 * 
 * 
 * 8.5 结构体嵌套结构体
 * 
 * 结构体中的成员可以是另一个结构体
 * 
 * 列如:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体
 * 
 * 
 * 8.6 结构体做函数参数
 * 
 * 将结构体作为参数向函数中传递
 * 
 * 值传递、地址传递
 * 
 * 
 * 8.7 结构体中const使用场景
 * 
 * 用const来防止误操作 void printStudent(const student *s){}
 * 
 * 防止地址传递修改原来的数据-->不可修改
 * 
 * 将函数中的形参改为指针,可以减少内存空间,而且不会复制新的副本出来
 * 
 */

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

//struct可以省略
struct Student {
	//成员列表

	//姓名
	string name;
	//年龄
	int age;
	//分数
	int score;
}s3;

//结构体嵌套结构体
struct Teacher {
	int id;
	string name;
	int age;
	struct Student stu;
};

void test5() {
	//第一种
	struct Student s1;
	s1.name = "张三";
	s1.age = 21;
	s1.score = 59;
	cout << "姓名:" << s1.name << " 年龄:" << s1.age << " 分数:" << s1.score << endl;

	//第二种
	struct Student s2 = {"李明",20,100};
	cout << "姓名:" << s2.name << " 年龄:" << s2.age << " 分数:" << s2.score << endl;

	//第三种
	s3.name = "李四";
	s3.age = 22;
	s3.score = 81;
	cout << "姓名:" << s3.name << " 年龄:" << s3.age << " 分数:" << s3.score << endl;
}

void test6() {
	struct Student s = {"张三",18,100};

	//结构体指针
	struct Student* p = &s;

	cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;
}

void test7() {
	Teacher t;
	t.id = 10000;
	t.name = "老李";
	t.age = 50;
	t.stu.name = "小王";
	t.stu.age = 18;
	t.stu.score = 99;

	cout << "老师姓名:" << t.name << " 老师编号:" << t.id << " 老师年龄:" << t.age << "\n"
		<< "老师辅导学生:" << t.stu.name << " 学生年龄:" << t.stu.age << " 学生分数:" << t.stu.score << endl;
}

//值传递
void printStudent1(struct Student s) {
	cout << "姓名:" << s.name << " 年龄:" << s.age << " 分数:" << s.score << endl;
}

//地址传递
void printStudent2(struct Student *p) {
	cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;
}

void test8() {
	struct Student s1;
	s1.name = "张三";
	s1.age = 21;
	s1.score = 59;

	printStudent1(s1);
	cout << endl;
	printStudent1(s1);

}

int main7() {

	test8();

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值