CStack栈模板封装示例

 1 #pragma once
 2 
 3 template <typename DATA>
 4 class CStack
 5 {
 6     DATA *m_pData;
 7     int m_nCount;
 8     int m_nTop; // 栈顶位置
 9 public:
10     CStack(int nCount = 5);
11     ~CStack();
12 
13     bool push(const DATA & d);
14     bool pop(DATA & d);
15     bool IsEmpty() { return m_nTop == -1; }
16     bool IsFull() { return m_nTop + 1 == m_nCount; }
17     
18 };
19 // 类外编写方式
20 template<typename DATA>
21 CStack<DATA>::CStack(int nCount)
22 {
23     m_nCount = nCount;
24     m_pData = new DATA[nCount];
25     m_nTop = -1;
26 }
27 
28 template<typename DATA>
29 CStack<DATA>::~CStack()
30 {
31     m_nCount = 0;
32     m_nTop = -1;
33     delete[]m_pData;
34 }
35 
36 template<typename DATA>
37 bool CStack<DATA>::push(const DATA &d)
38 {
39     if (IsFull())
40         return false;
41     m_pData[++m_nTop] = d;
42     return true;
43 }
44 
45 template<typename DATA>
46 bool CStack<DATA>::pop(DATA &d)
47 {
48     if (IsEmpty())
49         return false;
50     d = m_pData[m_nTop--];
51     return true;
52 }
原文地址:https://www.cnblogs.com/veis/p/12506564.html