[计算机科学经

Depth template typename t class node nodet allocate

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Stack<T,MAXSIZE>::Stack () : numElems(0) // ㆒開始並無任何元素 { // 不做任何事 } template <typename T, int MAXSIZE> void Stack<T,MAXSIZE>::push (T const& elem) { if (numElems == MAXSIZE) { throw std::out_of_range("Stack<>::push(): stack is full."); } elems[numElems] = elem; // 追加 ++numElems; // 元素總數加 1 } template <typename T, int MAXSIZE> void Stack<T,MAXSIZE>::pop () { if (numElems <= 0) { throw std::out_of_range("Stack<>::pop(): empty stack."); } --numElems; // 元素總數減 1 } C++ Templates - The Complete Guide 4.1 Nontype Class Template Parameters(非型別類別模板參數) 37 template <typename T, int MAXSIZE> T Stack<T,MAXSIZE>::top () const { if (numElems <= 0) { throw std::out_of_range("Stack<>::top(): empty stack."); } return elems[numElems - 1]; // 傳回最後㆒個元素 } 新加入的第㆓個 template parameter MAXSIZE 隸屬 int 型別,用來指定「容納 stack 元素」的那 個底部 array 的大小: template <typename T, int MAXSIZE> class Stack { private: // 元素 T elems[MAXSIZE]; ... }; push()便是使用 MAXSIZE 來檢查 stack 是否已滿: template <typename T, int MAXSIZE> void Stack<T,MAXSIZE>::push (T const& elem) { if (numElems =...
View Full Document

Ask a homework question - tutors are online