Stack4.hpp的代码如下:
#ifndef STACK4_HPP #define STACK4_HPP #include <iostream> #include <vector> #include <stdexcept> template <typename T, int MAXSIZE> class Stack { public: Stack(); void push(T const&); void pop(); T top() const; bool empty() const { return 0 == numElems; } bool full() const { return MAXSIZE == numElems; } private: T elems[MAXSIZE]; int numElems; }; template <typename T, int MAXSIZE> Stack<T, MAXSIZE>::Stack() : numElems(0) { } template <typename T, int MAXSIZE> void Stack<T, MAXSIZE>::push(T const& elem) { if (full()) { throw std::out_of_range("Stack<>::push(): stack is full"); } elems[numElems] = elem; ++numElems; } template <typename T, int MAXSIZE> void Stack<T, MAXSIZE>::pop() { if (empty()) { throw std::out_of_range("Stack<>::pop(): empty stack"); } --numElems; } template <typename T, int MAXSIZE> T Stack<T, MAXSIZE>::top() const { if (empty()) { throw std::out_of_range("Stack<>::top(): empty stack"); } return elems[numElems-1]; } #endif // STACK4_HPP
测试代码main.cpp:
#include <iostream> #include <string> #include <deque> #include <cstdlib> #include <typeinfo> #include "Stack4.hpp" using namespace std; int main() { try { Stack<int, 20> int20Stack; int20Stack.push(7); cout << int20Stack.top() << endl; int20Stack.pop(); Stack<int, 40> int40Stack; cout << "\nThe type of int20Stack: " << typeid(int20Stack).name() << endl << "The type of int40Stack: " << typeid(int40Stack).name() << endl; Stack<string, 40> string40Stack; string40Stack.push("Hello"); cout << endl << string40Stack.top() <<endl; string40Stack.pop(); string40Stack.pop(); } catch (std::exception const& ex) { cerr << "Exception: " << ex.what() << endl; return EXIT_FAILURE;// n stdlib.h } return 0; }
结果:
时间: 2024-10-16 07:12:39