C++結構體詳解
更新時間:2021年09月22日 11:54:17 作者:SamRol
這篇文章主要介紹了C++ 結構體與共用體的的相關資料,幫助大家更好的理解和學習c++,感興趣的朋友可以了解下,希望能夠給你帶來幫助
一、結構體的定義
struct Student { string name; int age; int score; };
二、創(chuàng)建具體的變量(3種)
struct Student s1; s1.name = "張三"; s1.age = 18; s1.score = 90;
struct Student s1 = {"李四" ,19 , 80 };
struct Student { string name; int age; int score; }s3; s3.name = "王五"; s3.age = 18; s3.score = 89;
三、結構體數組
struct Student stuArray[3] = { {"張三" , 20 , 92}, {"李四" , 18 , 89}, {"王五" , 24 , 95} }; stuArray[2].name = "趙六";// 把王五改為趙六 //遍歷結構體數組 for(int i =0; i < 3;i++) { cout << "姓名:" << stuArray[i].name << "年齡:" << stuArray[i].age << "分數:" << stuArray[i].score <<endl; }
四、結構體指針
利用操作符-> 可以通過結構體指針訪問結構體屬性。
struct Student s = {"張三", 18, 90}; struct Student *p = &s; //通過指針訪問結構體變量中的數據 cout << "姓名:" << p->name << endl;
五、結構體嵌套結構體
struct student { String name; int age; int score; } struct teacher { int id; String name; int age; struct student stu; }
teacher t; t.stu.name;
六、結構體做函數參數
1、值傳遞
void printStudent(struct Student s1) { cout << "姓名:" <<s1.name << "年齡:" << s1.age << "分數" << s1.score; } int main(){ struct Student s1; s1.name = "張三"; s1.age = 18; s1.score = 95; printStudent(s1); }
2、地址傳遞
void printStudent(struct Student * s1) { cout << "姓名:" << p->name << "年齡:" << p->age << "分數" << p->score; } int main(){ struct Student s1; s1.name = "張三"; s1.age = 18; s1.score = 95; printStudent(&s1); }
七、結構體中const使用場景
void printStudent(const Student * s1) { cout << "姓名:" << p->name << "年齡:" << p->age << "分數" << p->score; } int main(){ struct Student s1; s1.name = "張三"; s1.age = 18; s1.score = 95; printStudent(&s1); }
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!