- #include "stdafx.h"
- #include <stdexcept>
- #include <iostream>
- #include <string>
- using namespace std;
- template <class T, int MAX_SIZE>
- class CStack
- {
- public:
- CStack();
- ~CStack();
- public:
- void push(T const&);
- void pop();
- T top() const;
- bool empty() const;
- bool full() const;
- private:
- T m_arrData[MAX_SIZE];
- int m_nCurrPos;
- };
- template <class T, int MAX_SIZE>
- CStack<T, MAX_SIZE>::CStack():m_nCurrPos(0)
- {
- }
- template <class T, int MAX_SIZE>
- CStack<T, MAX_SIZE>::~CStack()
- {
- }
- template <class T, int MAX_SIZE>
- bool CStack<T, MAX_SIZE>::empty() const
- {
- return 0 == m_nCurrPos;
- }
- template <class T, int MAX_SIZE>
- bool CStack<T, MAX_SIZE>::full() const
- {
- return MAX_SIZE == m_nCurrPos;
- }
- template <class T, int MAX_SIZE>
- void CStack<T, MAX_SIZE>::push(const T &elem)
- {
- if (m_nCurrPos == MAX_SIZE)
- {
- throw out_of_range("Stack<>::push stack is full!");
- }
- m_arrData[m_nCurrPos++] = elem;
- }
- template <class T, int MAX_SIZE>
- void CStack<T, MAX_SIZE>::pop()
- {
- if (m_nCurrPos <= 0)
- {
- throw out_of_range("Stack<>::pop stack is empty!");
- }
- --m_nCurrPos;
- }
- template <class T, int MAX_SIZE>
- T CStack<T, MAX_SIZE>::top() const
- {
- if (m_nCurrPos <= 0)
- {
- throw out_of_range("Stack<>::pop stack is empty!");
- }
- return m_arrData[m_nCurrPos - 1];
- }
- int main()
- {
- CStack<int, 20> int20Stack;
- CStack<int, 40> int40Stack;
- CStack<string, 40> stringStack;
- //test int stack;
- int20Stack.push(7);
- cout << int20Stack.top() << endl;
- int20Stack.pop();
- //string stack;
- stringStack.push("hello");
- cout << stringStack.top() << endl;
- stringStack.pop();
- return 0;
- }
非类型类别模板参数
最新推荐文章于 2023-01-14 12:42:42 发布