結構體種const的使用場景(7)


作用:用const來防止誤操作

使用場景:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //定義學生結構體
 6 struct Student
 7 {
 8     string name;
 9     int age;
10     int score;
11 };
12 
13 //使用地址傳遞和引用的方式,可以減少內存空間,而且不會復制出新的副本來
14 void print_stu_info(const struct Student *p)
15 {
16     //p->age = 150;//用於地址傳遞和引用有形參改變,實參也改變的缺陷,為了彌補這個缺陷,所以使用const來修飾,來防止誤操作
17     cout << "姓名:" << p->name << "  年齡:" << p->age << " 分數:" << p->score << endl;
18 }
19 
20 
21 int main(void)
22 {
23     //創建結構體變量
24     struct Student s = {"張三",18,100};
25 
26     //通過函數來打印學生信息
27     print_stu_info(&s);
28 
29     system("pause");
30     return 0;
31 }

 


免責聲明!

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



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