①结构体的定义与应用 ② 结构体数组 ③结构体指针 ④结构体嵌套结构体

结构体的定义与应用

  • . 来访问结构体变量

结构体的的定义
struct student
{
int age;//年龄
string name;//姓名
int score;//分数
};

三种定义方式如下:

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

//结构体的的定义
struct student
{
    
    
	int age;//年龄
	string name;//姓名
	int score;//分数
}s3;

int main() {
    
    
	//创建结构体变量

	//用 . 来访问结构体变量

	//第一种:
	struct student s1 = {
    
     18, "梨花",89 };
	cout <<"年龄:"<< s1.age <<"  "<<"名字:" << s1.name <<"   "<<"分数:"<< s1.score << endl;

	//第二种:
	struct student s2;
	s2.age = 19;
	s2.name = "李四";
	s2.score = 90;
	cout << "年龄:" << s2.age << "  " << "名字:" << s2.name << "   " << "分数:" << s2.score << endl;

	//第三种:
	//在定义结构体的时候就定义变量
	s3.age = 25;
	s3.name = "Anna";
	s3.score = 100;
	cout << "年龄:" << s3.age << "  " << "名字:" << s3.name << "   " << "分数:" << s3.score << endl;
	return 0;
}

结构体数组

struct student stuArray[3]
{
{18, “李华” , 80},
{19,“张三”,89},
{20,“王五”,100}
};

//自定义修改变量
stuArray[2].name = “赵六”;
stuArray[2].age = 17;

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

//结构体的定义
struct student
{
    
    
	int age;//年龄
	string name;//姓名
	int score;//分数
};
int main()
{
    
    
	//数组变量
	struct student stuArray[3]
	{
    
    
		{
    
    18, "李华" , 80},
		{
    
    19,"张三",89},
		{
    
    20,"王五",100}
	};

	//自定义修改变量
	stuArray[2].name = "赵六";
	stuArray[2].age = 17;
	
	//输出变量中的数据
	for (int i = 0; i < 3; i++)
	{
    
    
		cout <<"年龄: "<< stuArray[i].age <<"   "
			<<"名字:" <<stuArray[i].name <<"   "
			<<"分数:"<< stuArray[i].score << endl;
	}
	return 0;
}

结构体指针

-> 访问结构体指针的属性

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

通过指针访问结构体变量中的数据
cout <<“学生的年龄:”<< p->age <<endl
<<“学生的名字:” << p->name <<endl
<<“学生的分数:” << p->score << endl;

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

// 用->访问结构体指针的属性

//创建结构体
struct student
{
    
    
	int age;//年龄
	string name;//姓名
	int score;//分数
};

int main()
{
    
    
	//创建结构体变量
	struct student s = {
    
    18,"李华",90};

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

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

	return 0;
}

结构体嵌套结构体

//老师的结构体
struct teather
{
int id;//id号码
string name;//名字
struct student s1;//老师辅导的学生
};

s.id = 1000;
s.name = “Amy”;
s.s1.age = 18;
s.s1.name = “Tom”;
s.s1.score = 90;

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

//一个老师辅导一个学生

//学生的结构体
struct student
{
    
    
	int age;//年龄
	string name;//名字
	int score;//分数
};

//老师的结构体
struct teather
{
    
    
	int id;//id号码
	string name;//名字
	struct student s1;//老师辅导的学生
};

int main() {
    
    

	//定义老师结构体的变量
	struct teather s;

	//定义变量对应的数据
	s.id = 1000;
	s.name = "Amy";
	s.s1.age = 18;
	s.s1.name = "Tom";
	s.s1.score = 90;

	cout << "教工编号:" << s.id << endl
		<<"教工名字:"<< s.name << endl 
		<<"管理的学生的年纪:"<< s.s1.age << endl
		<<"管理的学生的名字:" <<s.s1.name << endl
		<<"管理的学生的分数:" <<s.s1.score << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42198265/article/details/113844211