tsaiwn@magpie% g++ mystk.cpp tsaiwn@magpie% ./a.out 53770880 tsaiwn@magpie% cat -n mystk.cpp 1 //mystk.cpp --- CopyLeft by tsaiwn@csie.nctu.edu.tw 2 //Object Oriented Programming features: 3 // Encapsulation 4 // Information hiding 5 // Inheritance 6 // Polymorphism 7 // 8 class MyStack{ 9 public: 10 enum{NELEMENT=99}; 11 private: 12 int data[NELEMENT]; 13 int stkptr; 14 public: 15 MyStack(void){ stkptr= -1; } 16 void push(int); 17 int pop(void); 18 int top(void); 19 int empty(void){ return (stkptr <= -1) ;} 20 int isfull(void){ return (stkptr >= NELEMENT-1);} 21 }; 22 23 void MyStack::push(int x) 24 { 25 stkptr++; 26 data[stkptr] = x; 27 } 28 inline int MyStack ::top(void) 29 { 30 return data[stkptr]; 31 } 32 inline int MyStack ::pop(void) 33 { 34 if(stkptr> -1) --stkptr; 35 } 36 // 37 #include 38 //#include 39 int main( ){ 40 //stack x; 41 MyStack x; 42 x.push(880); 43 x.push(770); 44 x.push(53); 45 while(!x.empty()){ 46 cout << x.top(); x.pop(); 47 } 48 cout << endl; 49 } 50 // 此例是把 stack 與 主程式寫在一個檔案, 這是偷懶且不好的方法 51 // 正確方式應該把stack獨立, 且應把宣告寫在 .h 檔案, 實作寫 .cpp檔案 tsaiwn@magpie% g++ mystk.cpp tsaiwn@magpie% ./a.out 53770880 tsaiwn@magpie% exit