tsaiwn@magpie % g++ mymain2.cpp mystk2.cpp -Wno-deprecated tsaiwn@magpie % ./a.out 53770880 tsaiwn@magpie % cat -n mystk2.h 1 //mystk2.h --- with mystk2.cpp --- by tsaiwn@csie.nctu.edu.tw 2 //這是正確的寫法: 把宣告寫在 mystk2.h 這 header file, 3 // 實作堆疊的程式碼則寫到 mystk2.cpp 中, 4 //不過, 此例中仍留了兩個函數 empty( ) 與 isfull( ) 在 .h 檔案中, 5 //因為它們是直接寫在 class 內, 會自動變成 inline function. 6 // (會影響翻譯方式, 但不會影響執行的答案) 7 //此外, 要注意不但在 mystk2.cpp 中要 #include "mystk2.h" 8 //而且使用此堆疊的主程式之檔案也要 #include "mystk2.h" 9 // 10 class MyStack{ 11 public: 12 enum{NELEMENT=99}; 13 private: 14 int data[NELEMENT]; 15 int stkptr; 16 public: 17 MyStack(void){ stkptr= -1; } 18 void push(int); 19 void pop(void); 20 int top(void); 21 int empty(void){ return (stkptr <= -1) ;} 22 int isfull(void){ return (stkptr >= NELEMENT-1);} 23 }; // 注意別忘了分號 ";" tsaiwn@magpie % cat -n mystk2.cpp 1 // mystk2.cpp -- implementation of the stack (by tsaiwn@csie.nctu.edu.tw) 2 #include "mystk2.h" 3 void MyStack::push(int x) 4 { 5 stkptr++; 6 data[stkptr] = x; 7 } 8 int MyStack :: top(void) 9 { 10 return data[stkptr]; 11 } 12 //Actually, pop( ) function is a void function in C++ STL 13 void MyStack ::pop(void) 14 { 15 if(stkptr> -1) --stkptr; 16 } tsaiwn@magpie % cat -n mymain2.cpp 1 // mymain2.cpp -- by tsaiwn@csie.nctu.edu.tw 2 // g++ mymain2.cpp mystk2.cpp ; ./a.out 3 #include "mystk2.h" 4 //注意以下 iostream.h 為舊的寫法; 1999之後的 C++ 使用 5 // 且要記得寫 using namespace std; 6 #include 7 int main( ) { 8 MyStack x; // x is a Stack object 9 x.push(880); 10 x.push(770); 11 x.push(53); 12 while(!x.empty()){ 13 cout << x.top(); x.pop(); 14 } 15 cout << endl; 16 } tsaiwn@magpie % g++ mymain2.cpp mystk2.cpp -Wno-deprecated tsaiwn@magpie % ./a.out 53770880 tsaiwn@magpie % exit exit