一、結構體聲明
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。
用於設置只能讀不能寫。