类模板
类模板: 是对一批仅仅成员数据类型不同的类的抽象,程序员只要为这一批类所组成的整个类家族创建一个类模板,给出一套程序代码,就可以用来生成多种具体的类,(这类可以看作是类模板的实例),从而大大提高编程的效率。类模板的实例化就是模板类。
定义类模板的一般形式是:
template <类型名 参数名1,类型名 参数名2,…>
class 类名
{
类声明体
};
类模板的选择性实例化: 当我们用某一个类型实例化类模板得到的一个模板类时,模板类的成员方法根据我们的使用而选择性实例化。
实例:我们直接来用模板写一个顺序栈,它可以存储任何类型数据。
//Author:Mr.Rain
#include <iostream>
using namespace std;
template <typename T>
class SeqStack//模板名称+类型参数列表 = 类名称
{
public:
SeqStack<T>(int size = 10)//构造
: _pstack(new T[size])
, _top(0)
, _size(size)
{}
~SeqStack<T>()//析构
{
delete[]_pstack;
_pstack = nullptr;
}
SeqStack(const SeqStack<T> &stack)//拷贝构造
{
_top = stack._top;
_size = stack._size;
_pstack = new <T>[_size];
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[]_pstack;
_top = stack._top;
_size = stack._size;
_pstack = new T[_size];
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;
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;
}
};
/*也可以在类外实现
template<typename T>
void SeqStack<T>::push(const T &val)//入栈
{
if (full())
{
expand();
}
_pstack[_top++] = val;
}*/
int main()
{
//类模板的选择性实例化
//模板类:class SeqStack<int>{};
SeqStack<int> s1;
s1.push(20);
s1.push(78);
s1.push(32);
s1.push(15);
s1.pop();
cout << s1.top() << endl;
return 0;
}
测试一下:获取栈顶元素