template <typename T, int MAX_SIZE> class Stack { public: Stack() :elems(NULL) , top(0) , capacity(0) {} ~Stack() { delete[] elems; elems = NULL; } void Push(const T &elem) //压入元素 { //int size = sizeof(elems); checkCapacity(); if (top <= MAX_SIZE) { elems[top] = elem; top++; } else { printf("栈已满,无法添加数据\n"); } } void Pop() //弹出元素 { top = top - 1; if (top == -1) { printf("栈已空,没有数据可删除\n"); } } T &Top() //取栈顶 { return elems[top]; } const T &Top() const { return elems[top]; } bool Empty() const { return top == 0; } void checkCapacity() { if (top >= capacity) { capacity = capacity > 0 ? capacity * 2 : 3; T* tmp = new T[capacity]; for (int i = 0; i < top; i++) { tmp[i] = elems[i]; } delete[] elems; elems = tmp; } } private: T *elems; //使用数组的方式存储 int top; int capacity; };