生活随笔
收集整理的這篇文章主要介紹了
                                
C++学习笔记25——结构体的定义和使用,结构体数组,结构体指针
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
 
                                
                            
                            
                            結構體
 
結構體的基本概念
 
結構體屬于用戶自定義的數據類型,允許用戶存儲不同的數據類型
 
結構體的定義和使用
 
語法:struct 結構體名 {結構體成員列表};
 通過結構體創(chuàng)建變量的方式有三種:
 struct 結構體名 變量名
 struct 結構體名 變量名 = {成員1值,成員2值…}
 定義結構體時順便創(chuàng)建變量
 示例:
 
#include <iostream>
using namespace std
;
struct Student 
{string name
;int age
;int score
;
}s3
;
int main(){struct Student s1
;s1
.name 
= "張三";s1
.age 
= 18;s1
.score 
= 100;cout 
<< "姓名:" << s1
.name 
<< " 年齡:"<< s1
.age
<<" 分數:"<<s1
.score 
<<endl
;struct Student s2 
= {"李四",20,80};cout 
<< "姓名:" << s2
.name 
<< " 年齡:" << s2
.age 
<< " 分數:" << s2
.score 
<< endl
;s3
.name 
= "王五";s3
.age 
= 17;s3
.score 
= 95;cout 
<< "姓名:" << s3
.name 
<< " 年齡:" << s3
.age 
<< " 分數:" << s3
.score 
<< endl
;system("pause");return 0;
}
 
 
 總結:1.定義結構體時的關鍵字struct,不可省略
 2.創(chuàng)建結構體變量時,關鍵字struct可以省略
 3.結構體變量利用操作符"."訪問成員
 
 
結構體數組
 
作用:將自定義的結構體放入到數組中方便維護
 語法:struct 結構體名 數組名[元素個數] = {{},{},...{}}
 示例:
 
#include <iostream>
#include <string>
using namespace std
;
struct Student 
{string name
;int age
;int score
;
};int main(){struct Student stuArray
[3] = { {"張三",18,100},{"李四",20,80},{"王五",17,95} };stuArray
[2].name 
= "趙六";stuArray
[2].age 
= 80;stuArray
[2].score 
= 60;for (int i 
= 0; i 
< 3; i
++) {cout 
<< "姓名:" << stuArray
[i
].name 
<< " 年齡:" << stuArray
[i
].age 
<< " 分數:" << stuArray
[i
].score 
<< endl
;}system("pause");return 0;
} 
運行結果:
 
結構體指針
 
作用:通過指針訪問結構體中的成員
 
利用操作符->可以通過結構體指針訪問結構體屬性
 示例:
 
#include <iostream>
#include <string>
using namespace std
;
struct Student 
{string name
;int age
;int score
;
};int main(){struct Student s 
= { "張三",18,100 };Student
* p 
= &s
;cout 
<< "姓名:" << p
->name 
<< " 年齡:" << p
->age 
<< " 分數:" << p
->score 
<< endl
;system("pause");return 0;
}
 
運行結果:
 
                            總結
                            
                                以上是生活随笔為你收集整理的C++学习笔记25——结构体的定义和使用,结构体数组,结构体指针的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。