头文件 stdafx.h :
1 #ifndef STACK_H_ 2 3 #define STACK_H_ 4 5 typedef unsigned long Item; 6 7 class Stack 8 { 9 static const int MAX = 10; //或者使用等价语句 enum {MAX = 10}; 10 Item items[MAX]; 11 int top; 12 13 public: 14 Stack(); 15 bool is_empty()const; 16 bool is_full()const; 17 bool push(const Item & item); 18 bool pop(Item & item); 19 }; 20 21 22 #endif
类的成员定义 stdafx.cpp :
1 #include "stdafx.h" 2 3 Stack::Stack() 4 { 5 top = 0; 6 } 7 8 bool Stack::is_empty()const 9 { 10 return top == 0; 11 } 12 13 bool Stack::is_full()const 14 { 15 return top == MAX; 16 } 17 18 19 bool Stack::push(const Item & item) 20 { 21 if (top < MAX) 22 { 23 items[top++] = item; 24 return true; 25 } 26 else 27 { 28 return false; 29 } 30 } 31 32 33 bool Stack::pop(Item & item) 34 { 35 if (top > 0) 36 { 37 item = items[--top]; 38 return true; 39 } 40 else 41 { 42 return false; 43 } 44 }
实现细节 run.cpp :
1 #include "stdafx.h" 2 #include<iostream> 3 #include<cctype> 4 5 6 7 int main() 8 { 9 using namespace std; 10 Stack st; 11 char ch; 12 unsigned long po; 13 cout << "输入\"A\"来添加一个购买序号\n" 14 << "\"p\"来处理po,\"Q\"来结束" << endl; 15 while (cin >> ch && toupper(ch) != 'Q') 16 { 17 while (cin.get() != '\n') 18 continue; 19 if (!isalpha(ch)) 20 { 21 cout << '\a'; 22 continue; 23 } 24 switch (ch) 25 { 26 case 'a': 27 case 'A':cout << "输入一个po数: "; 28 cin >> po; 29 if (st.is_full()) 30 cout << "堆栈已满!" << endl; 31 else 32 st.push(po); 33 break; 34 35 case 'p': 36 case 'P': 37 if (st.is_empty()) 38 cout << "堆栈为空!" << endl; 39 else 40 { 41 st.pop(po); 42 cout << "PO #" << po << "poped\n"; 43 } 44 break; 45 46 } 47 cout << "输入\"A\"来添加一个购买序号\n" 48 << "\"p\"来处理po,\"Q\"来结束" << endl; 49 50 } 51 cout << "游戏结束!" << endl; 52 system("pause"); 53 return 0; 54 }
运行结果实例:

浙公网安备 33010602011771号