作用:用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 }