结构体的定义:
struct 变量名
{
类型 变量名;
...
};
创建结构体变量的三种方法:
#include<string.h>
#include<iostream>
using namespace std;
struct student
{
string name;
int weight;
int length;
}A3;//(顺便创建结构体!!)
int mian()
{
//方式1.创建结构体+赋值
struct student A1;
A1.length = 160;
A1.name = "lily";
A1.weight = 45;
//方式2.直接 创建赋值
struct student A2 = { "姚莉",167,46 };
//3.顺便创建结构体
A3.length = 177;A3.name = "yuyu";A3.weight = 67;
system("pause");
return 0;
}
赋值时,用符号 . 访问
结构体数组:定义,创建,赋值,遍历
如:
#include<iostream>
#include<string.h>
using namespace std;
//定义结构体数组
struct student
{
string name;
int age;
int grade;
};
int main()
{
//创建结构体数组
struct student stuArr[4] = {
{"liyu",12,2} ,{"黎明",11,1}, {"tity",14,4} ,{"kiky",17,7} };
//赋值或更改
stuArr[2].name = "TiTy";
stuArr[2].age = 16;
stuArr[2].grade = 6;
//遍历
for(int i = 0;i < 4;i++)
{
cout << "name:" << stuArr[i].name
<< " age:" << stuArr[i].grade
<< " grade:" << stuArr[i].age<<endl;
}
system("pause");
return 0;
}
结构体指针_指针指向,指针访问
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
int main()
{
//创建结构体变量
student S1 = { "lily",15,97 };
//通过指针指向结构体变量
student* p = &S1;
//指针访问结构体变量中的属性
cout << "name: " << p->name <<" age:"<< p->age <<" score:"<< p->score << endl;
system("pause");
return 0;
}
结构体可以通过 -> 对结构体变量进行访问。
结构体嵌套结构体
作用:结构体中的成员越是结构体。(套娃)
#include<iostream>
#include<string.h>
using namespace std;
struct student
{
string name;
int age;
int score;
};
struct teacher
{
string name;
int age;
int score;
struct student S;
};
int main()
{
//创建teacher结构体
//struct teacher tea;
teacher tea;
//赋值
tea.name = "lily";
tea.age = 76;
tea.score = 100;
tea.S.name = "taizi";
tea.S.age = 13;
tea.S.score = 98;
//访问
cout << "老师的名字:" << tea.name << " 老师的年龄:" << tea.age << " 老师的分数:" << tea.score << " 老师指导的学生的名字:" << tea.S.name << " 年龄:"
<< tea.S.age << " 分数:" << tea.S.score << endl;
system("pause");
return 0;
}
结构体做函数参数
#include<string.h>
#include<iostream>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void str(student S)
{
S.age = 12;
S.name = "haotian";
S.score = 88;
cout << S.age <<" " << S.name<<" " << S.score << endl;
}
void str1(student *S)
//将函数中的形参改为指针,可以减少内存空间,而且不会复制新的副本出来
{
S->age = 17;
S->name = "ziyang";
S->score = 90;
cout << S->age<< " " << S->name << " " << S->score << endl;
}
int main()
{
student A;
A.age = 1;
A.name = "ziyue";
A.score = 87;
str(A);//传值 ——不变实参
//str1(&A);//传址 —改变实参
cout << A.age << " " << A.name << " " << A.score << endl;
system("pause");
return 0;
}
结构体中的const使用场景
const:防止误改
例子:
void str(const student *S)
{
S->age=12;//加入const之后,一旦修改就会报错,可以防止误操作
}