类模板
模板提供参数化(parameterized)类型,即能够将类型名作为参数传递给接收方来建立类或函数,例如,将类型名int传递给Queue模板,可以让编译器构造一个队int进行排序的Queue类。
1 定义类模板
见以下代码:
template <class type>
class Stack
{
private:
enum {Max = 10};
Type items[Max];
int top;
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item);
bool pop(Type & item);
};
template <class Type>
Stack<Type>::Stack()
{
top = 0;
}
template <class Type>
bool Stack<Type>::isempty()
{
return top==0;
}
template<class Type>
bool Stack<Type>::isfull()
{
return top==Max;
}
...
2 模板的使用
#include <iostream>
#include <stacktp.h>
int main()
{
Stack<int>st;//create an empty stack for int;
...
return 0;
}