结构体的处理(以c++primer plus 第六章习题4为例)
1 const unsigned int strsize = 50; 2 struct bop //结构体就像一个数据类型如int 使用前应该先给他一个变量如本题中的bop 3 { 4 char fullname[strsize]; // real name 5 char title[strsize]; // job title 6 char bopname[strsize]; // secret BOP name 7 int preference; // 0 = fullname, 1 = title, 2 = bopname 8 }; //如果在这里用 typedef struct bop{}bop1; 在下面初始化和传参的时候就可以将 const struct bop 变为const bop1; 9 void display_by_name(const struct bop *bopArray, unsigned int size) //const 最小授权 结构体不会被改变 boparray还是一个数组 数组在传递的时候 一般用地址传递 就是指针传递 传递数组时要带上它的数组规模 10 { 11 for (size_t i = 0; i < size; i++) 12 { 13 cout << bopArray[i].fullname << endl; //调用结构体中成员的方式 14 } 15 } 16 void display_by_title(const struct bop *bopArray, unsigned int size) 17 { 18 for (size_t i = 0; i < size; i++) 19 { 20 cout << bopArray[i].title << endl; 21 } 22 } 23 void display_by_bopname(const struct bop *bopArray, unsigned int size) 24 { 25 for (size_t i = 0; i < size; i++) 26 { 27 cout << bopArray[i].bopname << endl; 28 } 29 } 30 void display_by_preference(const struct bop *bopArray, unsigned int size) 31 { 32 for (size_t i = 0; i < size; i++) 33 { 34 if (bopArray[i].preference == 0) 35 { 36 cout << bopArray[i].fullname << endl; 37 } 38 else if (bopArray[i].preference == 1) 39 { 40 cout << bopArray[i].title << endl; 41 } 42 else if (bopArray[i].preference == 2) 43 { 44 cout << bopArray[i].bopname << endl; 45 } 46 } 47 } 48 void p6_4(void) 49 { 50 const struct bop bopArray[5] = { //给结构体变量初始化的方式 51 {"Wimp Macho", "YYY", "Y----", 0}, 52 {"XXXXXXXX", "2XXXX", "3XXXXX", 1}, 53 {"AAAAAAAA", "2AAAA", "3AAAAA", 2}, 54 {"BBBBBBBB", "2BBBB", "3BBBBB", 0}, 55 {"CCCCCCCC", "4CCCC", "3CCCCC", 1} 56 }; 57 char choice = 0; 58 59 cout << "Benevolent Order of Proframers Report" << endl; 60 cout << left << setw(30) << "a. display by name" << "b. display by title" << endl; 61 cout << left << setw(30) << "c. display by bopname" << "d. display by preference" << endl; 62 cout << left << setw(30) << "q. quit" << endl; 63 cout << "Enter your choice:"; 64 65 while (cin >> choice) 66 { 67 if (choice == 'q') 68 { 69 break; 70 } 71 switch (choice) 72 { 73 case 'a': 74 display_by_name(bopArray, 5); 75 break; 76 77 case 'b': 78 display_by_title(bopArray, 5); 79 break; 80 81 case 'c': 82 display_by_bopname(bopArray, 5); 83 break; 84 85 case 'd': 86 display_by_preference(bopArray, 5); 87 break; 88 89 default: 90 break; 91 } 92 cout << "Next choice:"; 93 } 94 cout << "Bye!" << endl; 95 return; 96 }