#pragma once
#include <exception>
using namespace std;
class underflow : public exception
{
const char * what() const
{
return "栈下溢";
}
};
class overflow : public exception
{
const char * what() const
{
return "栈上溢";
}
};
template <class T> class mystack {
public:
mystack(int s) :size(s) { top = new T*[size]; base = top; };//构造大小为s的栈
mystack() :size(12) { top = new T*[size]; base = top; };//重载,默认栈大小为12
~mystack();
int push(T&);//对外的入栈接口
T pop();//对外的出栈接口,包括了抛出异常
int getsize() { return size; };
bool isfull() { return (top == &base[size - 1]); }
bool isempty() { return empty; }
private:
const int size;
T**top;
T**base;
bool empty=1;
protected:
T popr() ;//真正的pop函数,但不包括抛出异常,这是为了能够在析构函数中调用
};
template <class T> mystack<T>::~mystack()
{
while (!empty)popr();
delete[]base;
}
template <class T> int mystack<T>::push(T& e)
{
if (empty == 1) empty = 0;
if (top >&base
栈的C++模板实现,能够支持不同类型的元素
最新推荐文章于 2022-09-06 20:39:42 发布
