5.类模板

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值