一、结构体声明
struct Student
{
//成员列表
string name;
int age;
int score;
}; //s3;定义时直接声明
int main()
{
struct Student s1;
//法一、直接赋值
s1.name = "Apple";
s1.age = 10;
//法二、直接声明
struct Student s2 = {"Banana", 19, 80}; //不可跳着声明
}
二、结构体数组
//创建结构体数组
int main()
{
struct Student stuArray[3] =
{
{"Apple", 19, 80},
{"Banana", 18, 99},
{"Cat", 17, 70}
}; //注意逗号,分号的位置
}
//给结构数组中赋值
int main()
{
struct Student stuArray[3] =
{
{"Apple", 19, 80},
{"Banana", 18, 99},
{"Cat", 17, 70}
};
stuArray[0].name = "Dog";
cout << stuArray[0].name << stuArray[0].score <<endl;
system("pause");
}
//遍历结构体数组:for循环
三、结构体指针
int main()
{
struct Student stuArray[3] =
{
{"Apple", 19, 80},
{"Banana", 18, 99},
{"Cat", 17, 70}
};
stuArray[0].name = "Dog";
cout << stuArray[0].name << stuArray[0].score <<endl;
//结构体指针
Student* p = &stuArray[0]; //定义
int a = p -> score; //访问 ->
cout << a <<endl;
system("pause");
}
四、结构体嵌套结构体
struct Student
{
//成员列表
string name;
int age;
int score;
};
struct Teacher
{
int id;
string name;
int age;
struct Student stu;
};
五、结构体作为函数参数
结构体作为函数参数有值传递和地址传递两种。
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Student
{
//成员列表
string name;
int age;
int score;
};
//值传递
void printStudent(struct Student s)
{
s.name = "Banana";
cout << "name: " << s.name << "age: " << s.age << "score: " << s.score <<endl;
}
//地址传递
void printStudent2(struct Student* p)
{
//p->name = "Banana";
cout << "name: " << p->name << "age: " << p->age << "score: " << p->score << endl;
}
int main()
{
struct Student s;
s = {"Apple", 20, 89};
printStudent(s);
struct Student* p = &s;
printStudent2(p);
cout << "name: " << p->name << "age: " << p->age << "score: " << p->score << endl;
system("pause");
}
六、结构体中使用const场景
用于防止误操作。
因为值传递浪费空间,所以一般使用地址传递。
如果函数使用了地址传递,函数内操作会改变实参值,为了防止实参被乱修改,使用const。
用于设置只能读不能写。