結構體-結構體中const使用場景


作用:用const來防止誤操作

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 struct student
 6 {
 7     string name;
 8     int age;
 9     int score;
10 };
11 
12 //  將函數中的形參改為指針,可以減少內存空間,而且不會復制新的副本出來
13 void printStudents(const student *s)
14 {
15     // s->age = 150; 加入const之后,一旦有修改的操作就會報錯,可以防止我們的誤操作
16     cout << "姓名:" << s->name << " 年齡:" << s->age << " 得分:" << s->score << endl;
17 }
18 
19 int main()
20 {
21     student s = { "張三",15,70 }; // 創建結構體變量
22     printStudents(&s);
23     cout << "主函數中張三的年齡為:" << s.age << endl;
24     return 0;
25 }

程序輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM