有C基础学习C++第四天(结构体)

1.结构体数组
2.结构体指针

#include <iostream>
using namespace std;

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


int main()
{
	//结构体数组
	//1.创建
	struct Student stuArray[] =
	{
		{"张三",18,10},
		{"李四",10,1090},
		{"王五",88,125},
	};
	//2.赋值
	stuArray[0].name = "蔡徐坤";
	stuArray[1].age = 66;
	stuArray[2].score = 25;
	//3.便历
	for (int i = 0; i < 3; i++) {
		cout << stuArray[i].name 
			 << "年龄:" << stuArray[i].age 
			 << "分数:" << stuArray[i].score << endl;
	}

	cout << "*********************" << endl;

	//结构体指针
	//1.创建
	struct Student stu1 = { "坤坤",21,20 };
	//2.指针指向结构体变量
	Student* p = &stu1;
	//3.指针访问结构体变量
	//通过结构体指针访问结构体中的属性,需要利用 ‘->’
	cout << p->name
		<< "年龄:" << p->age
		<< "分数:" << p->score << endl;

	system("pause");
	return 0;

}

结果

蔡徐坤年龄:18分数:10
李四年龄:66分数:1090
王五年龄:88分数:25
*********************
坤坤年龄:21分数:20
请按任意键继续. . .

3.结构体嵌套
4.结构体做函数参数

#include <iostream>
using namespace std;

//结构体嵌套
struct Student
{
	string name;
	int age;
	int score;
};

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

//结构体做函数参数
//1.值传递
void printStudent(struct Student s)
{
	s.age = 100;//修饰形参,实参不会改变
	cout << "子函数中 姓名:" << s.name
		<< "年龄:" << s.age
		<< "分数:" << s.score << endl;
}
//2.地址传递
void printStudent2(struct Student* s)//用指针还会减少内存空间
{
	s->age = 100;//修饰形参会改变实参
	cout << "子函数2中 姓名:" << s->name
		 << "年龄:" << s->age
		 << "分数:" << s->score << endl;
}

int main()
{
	//结构体嵌套
	Teacher t1;
	t1.id = 25410;
	t1.name = "老王";
	t1.age = 35;
	t1.s1.name = "小王";
	t1.s1.age = 20;
	t1.s1.score = 100;

	//结构体做函数参数
	printStudent(t1.s1);
	cout << "main函数值传递中 姓名:" << t1.s1.name
		<< "年龄:" << t1.s1.age
		<< "分数:" << t1.s1.score << endl;
	printStudent2(&t1.s1);
	cout << "main函数地址传递中 姓名:" << t1.s1.name
		<< "年龄:" << t1.s1.age
		<< "分数:" << t1.s1.score << endl;

	system("pause");
	return 0;

}

结果

子函数中 姓名:小王年龄:100分数:100
main函数值传递中 姓名:小王年龄:20分数:100
子函数2中 姓名:小王年龄:100分数:100
main函数地址传递中 姓名:小王年龄:100分数:100
请按任意键继续. . .
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值