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