[计算机科学经

56 default call arguments template parameter fill t

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: () const { if (elems.empty()) { throw std::out_of_range("Stack<>::top: empty stack"); } return elems.back(); // 傳回最後元素的拷貝 } C++ Templates - The Complete Guide 3.2 使用 Class Template Stack 25 當然,你也可以把任何 class templates 的成員函式實作碼寫在 class 宣告式㆗,形成㆒個 inline 函 式。例如: template <typename T> class Stack { ... void push(T const& elem) { elems.push_back(elem); // 將傳入的元素 elem 附加於尾 } ... }; 3.2 使用 Class Template S tack 為了使用 class template object,你必須明確指出其 template arguments。㆘面例子說明如何使用 Stack<> class template: // basics/stack1test.cpp #include #include #include #include <iostream> <string> <cstdlib> "stack1.hpp" int main() { try { Stack<int> intStack; Stack<std::string> stringStack; // stack of ints // stack of strings // 操控 int stack intStack.push(7); std::cout << intStack.top() << std::endl; // 操控 string stack stringStack.push("hello"); std::cout << stringStack.top() << std::endl; stringStack.pop(); stringStack.pop(); } catch (std::exception const& ex) { std::cerr << "Exception: " << ex.what() << std::endl; return EXIT_FAILURE; // 傳回錯誤狀態碼 } } C++ Templates - The Complete Guide...
View Full Document

Ask a homework question - tutors are online