C++的模版类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ns708865818/article/details/77871964

1.不能将模版类的成员函数放在独立的实现文件中,必须将声明和定义放在一起。以前可以用export关键字,现在不行了。

如下面的例子。

#ifndef STACKP_H_
#define STACKP_H_
template <class Type>
{
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>::push(const Type & item)
{
	if(top<MAX)
	{
		items[top++]=item;
		return true;
	}
	 return false;
}
template <class Type>
bool Stack<Type>::pop(Type & item)
{
	if(top>0)
	{
		item=item[--top];
		return true;
	}
	return false;
}
#endif
2.仅在程序中包含模板并不能生成模板类,而必须请求实例化。如下所示:

Stack<int> kernels;
Stack<int> colonels;


猜你喜欢

转载自blog.csdn.net/ns708865818/article/details/77871964