类模板如何实例化问题
本帖最后由 chenxue1111 于 2013-12-06 11:17:45 编辑 按数据结构写了一个栈的类模板,把模板类的实现整个放在了一个头文件里头
#include <iostream>
#include <assert.h>
using namespace std;
const int StackIncreament = 20;
template<typename T>
class SeqStack //: public Stack<T>
{
private:
T* Elements;
int top;
int MaxSize;
void OverflowProcess();
public:
SeqStack(int sz = 50);
~SeqStack(){delete []Elements;};
void Push(const T&);
bool Pop(T& );
bool GetTop(T&);
int GetSize()const{return top + 1;}
bool IsEmpty()const {return top == -1?1:0;}
bool IsFull()const {return top == MaxSize -1 ? 1:0}
void MakeEmpty(){top = -1;}
friend ostream& <<(ostream& os, SeqStack<T>&s);
};
template<typename T>
void SeqStack<T>::OverflowProcess()
{
MaxSize = MaxSize + StackIncreament;
T* NewArry = new T[MaxSize];
assert(NewArry != NULL);
for (int i = 0; i != top + 1; i++)
{
NewArry[i] = Elements[i];
}
delete []Elements;
Elements = NewArry;
}
template<typename T>
SeqStack<T>::SeqStack(int sz):MaxSize(sz),top(-1)
{
Elements = new T[sz];
assert(Elements != NULL);
}
template<typename T>
void SeqStack<T>::Push(const T& x)
{
if (IsFull())
{
OverflowProcess();
}
top++;
Elements[top] = x;
}
template<typename T>
bool SeqStack<T>::Pop(T& x)
{
if (IsEmpty())
{
return false;
}
x = Elements[top];
top--;
return true;
}
template<typename T>
bool SeqStack<T>::GetTop(T& x)
{
if (IsEmpty())
{
return false;
}
x = Elements[top];
return true;
}
template<typename T>
ostream& operator<<(ostream& os,SeqStack<T>& s)
{
os<<"top = "<<s.top<<endl;
for (int i = 0; i != s.top + 1; i++)
{
os<<i<<":"<<s.Elements[i]<<endl;
}
return os;
}
#include <iostream>
#include"SeqStack.h"
using namespace std;
int main()
{
return 0;
}
SeqStack<int> istack;//栈中存储的element为int型
SeqStack<string> sstack;//string型
cout<<istack.IsEmpty();
cout<<sstack.IsFull();