结构体

119 阅读1分钟

语法:

struct 结构体 { 结构体成员列表 };

1.创建结构体变量是三种方法:

//创建学生数据类型
struct Student
{
	//姓名
	string name;
	//年龄
	int age;
	//分数
	int score;
}s3;	//顺便定义结构体变量



//1.通过学生类型创建具体的学生,这个struct可以省略
	struct Student s1;
	//给s1属性赋值,通过.访问结构体变量中的属性
	s1.name = "张三";
	s1.age = 18;
	s1.score = 100;

	//输出结构体变量
	cout << "姓名:" << s1.name << "年龄:" << s1.age << "分数:" << s1.score << endl;

	//2.直接赋值,这个struct可以省略
	struct Student s2 = { "李四",16,99 };
	cout << "姓名:" << s2.name << "年龄:" << s2.age << "分数:" << s2.score << endl;

	//3.在定义结构体的时候顺便定义
	s3.name = "王无";
	s3.age = 33;
	s3.score = 45;
	cout << "姓名:" << s3.name << "年龄:" << s3.age << "分数:" << s3.score << endl;

3.创建结构体数组

        //创建结构体数组
	struct Student stuArray[3] = {
		{"张三",32,78},
		{"李四",22,88},
		{"王五",26,99}
	};
	//给结构体里面的元素赋值
	stuArray[2].name = "lili";

	//遍历结构体数组
	for (int i = 0; i < 3; i++)
	{
		cout << "姓名:" << stuArray[i].name
			<< "年龄:" << stuArray[i].age
			<< "分数:" << stuArray[i].score << endl;
	}

4.结构体指针

作用:通过指针访问结构体中的成员

利用操作符->可以通过结构体指针访问结构体属性

        //结构体指针
	Student s1 = { "张三",23,88 };
	//定义结构体指针
	Student * p = &s1;
	//通过指针访问结构体属性
	cout << "姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score << endl;

5.结构体嵌套结构体

//创建学生数据类型
struct Student
{
	//姓名
	string name;
	//年龄
	int age;
	//分数
	int score;
};	//顺便定义结构体变量

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



        //结构体嵌套结构体
	//定义老师结构体变量
	Teacher t;
	t.name = "老万";
	t.age = 30;
	t.id = "123";
	t.stu.name="小王";
	t.stu.age = 10;
	t.stu.score = 99;

6.结构体作为函数的参数

//结构体作为函数的参数
//1.值传递
void printStudent1(Student s) {

	cout << "姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << endl;
}

//2.地址传递
void printStudent2(Student * p) {

	cout << p->name << p->age << p->score << endl;
}



        //调用函数
	Student s = { "张三",34,100 };
	printStudent1(s);
	printStudent2(&s);

7.const修饰防止误操作

//2.地址传递:将函数中的形参改为指针,没有copy减少内存空间的使用
//为了防止误操作加上:const
void printStudent2(const Student * p) {

	//报错,不允许写操作
	p->age = 30;
	cout << p->name << p->age << p->score << endl;
}