//mystk.cpp -- CopyLeft by tsaiwn@csie.nctu.edu.tw //Object Oriented Programming features: // Encapsulation // Information hiding // Inheritance // Polymorphism // class MyStack{ public: enum{NELEMENT=99}; private: int data[NELEMENT]; int stkptr; public: MyStack(void){ stkptr= -1; } void push(int); int pop(void); int top(void); int empty(void){ return (stkptr <= -1) ;} int isfull(void){ return (stkptr >= NELEMENT-1);} }; void MyStack::push(int x) { stkptr++; data[stkptr] = x; } inline int MyStack ::top(void) { return data[stkptr]; } inline int MyStack ::pop(void) { if(stkptr> -1) --stkptr; } //注意以下 iostream.h 為舊的寫法; 1999之後的 C++ 使用 #include //#include int main( ){ //stack x; MyStack x; x.push(880); x.push(770); x.push(53); while(!x.empty()){ cout << x.top(); x.pop(); } cout << endl; } // 此例是把 stack 與 主程式寫在一個檔案, 這是偷懶且不好的方法 // 正確方式應該把stack獨立, 且應把宣告寫在 .h 檔案, 實作寫 .cpp檔案