#include <iostream>
using namespace std;
template<typename T=int>
class SeqStack //模板名称+类型参数列表=类名称
{
public:
//构造和析构函数不用加<T>,其他出现模板的地方都应加上类型参数列表
SeqStack(int size = 10)
:_pstack(new T[size])
,_top(0)
,_size(size)
{}
~SeqStack()
{
delete[]_pstack;
_pstack = nullptr;
}
SeqStack(const SeqStack<T>& stack)
: _top(stack._top)
, _size(stack._size)
{
_pstack = new T[_size];
//不要用memcopy拷贝
for (int i = 0; i < top; ++i)
{
_pstack[i] = stack._pstack[i];
}
}
SeqStack<T>& operator=(const SeqStack<T>& stack)
{
if (this == &stack)
return *this;
delete[] stack;
_top = stack._top;
_size = stack._size;
_pstack = new T[_size];
//不要用memcopy拷贝
for (int i = 0; i < top; ++i)
{
_pstack[i] = stack._pstack[i];
}
return *this;
}
void push(const T& val)
{
if (full())
expand();
_pstack[_top++] = val;
}
void pop()
{
if (empty())
return;
--_top;
}
T top()const
{
if (empty())
throw "stack is empty!"; //抛异常也代表函数逻辑结束
return _pstack[_top - 1];
}
bool full()const
{
return _top == _size;
}
bool empty() const
{
return _top == 0;
}
private:
T* _pstack;
int _top;
int _size;
//顺序栈底层数组是安装2倍的方式扩容
void expand()
{
T* ptmp = new T[_size * 2];
for (int i = 0; i < _top; i++)
{
ptmp[i] = _pstack[i];
}
delete[] _pstack;
_pstack = ptmp;
_size *= 2;
}
};
int main()
{
SeqStack<int> s;
s.push(20);
s.push(40);
s.push(50);
s.pop();
cout << s.top() << endl;
return 0;
}