结构体数组,结构体指针,结构体嵌套结构体

     一、结构体数组

          存放相同组合的大量数据时,可以通过创建结构体数组的方式进行;   

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


int main()
{
	Student stuArray[3] =
	{
		{"汪苏泷",34,10000},
		{"不分手的恋爱",12,10000},
		{"还是想念",0,10000}
	};

	for (int i = 0; i < 3; i++)
	{
		cout << "	name:	" << stuArray[i].name
			<< "	age:	" << stuArray[i].age
			<< "	score:	" << stuArray[i].score << endl;
	}

	system("pause");

	return 0;

}

二、结构体指针

        可以通过指针来访问结构体中的成员,利用‘->’符号;        

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


int main()
{
	//创建结构体变量
	Student s = {"汪苏泷",34,10000};

	//通过指针指向结构体变量
	Student* p = &s;

	//通过指针访问结构体变量中的数据
	cout << "姓名:" << p->name << "	年龄:" << p->age << "	分数:" << p->score << endl;

	system("pause");

	return 0;

}

三、结构体嵌套结构体

        通过两个‘.’,可以访问结构体中结构体的数据;例如如下代码是在teacher结构体中嵌套了stuent结构体;

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


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

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

int main()
{
	Teacher t;
	t.id = 0001;
	t.age = 18;
	t.name = "李雪琴";
	t.stu.age = 34;
	t.stu.name = "汪苏泷";
	t.stu.score = 10000;

	cout << "姓名:" << t.name << "	年龄:" << t.age <<  "	id:" << setfill('0') << setw(4) << t.id<< endl;
	cout << "学生姓名:" << t.stu.name << "	年龄:" << t.stu.age<< "	分数:" << t.stu.score << endl;

	system("pause");

	return 0;

}

运行结果如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值