今天我终于抽出时间搞定了有生以来第一个自制的模版,功能很简单,就是实现一个栈的基本操作,取顶,压栈,弹栈。我发现模版这个东西其实挺好用的,我想以后我可以用这玩意儿实现很多STL中未提供的数据结构了,尽管估计做得效率会很低,但我只是为了玩。嘻嘻……
/* Stack.h
* Writen by Sam Liang
* At 30th Sept. 2006
* A template which realize a stack. Just a test!
*/
const int MaxSize = 100;
template <class T>
class Stack
{
public:
// constructors
Stack(int itsSize = MaxSize);
Stack(const Stack &rhs);
~Stack() {delete [] pType;}
// operators
Stack& operator = (const Stack&);
// member functions
int GetSize() const {return itsSize;}
T const TOP() ;
void PUSH(T element);
void POP() const
{
if(top != 0){
top--;
}
else
cout<<"ERROR: The stack is empty!"<<endl;
};
private:
T* pType;
int itsSize;
int top;
};
/*********************************************************
* Main Constructor
*********************************************************/
template <class T>
Stack<T>::Stack(int size):
itsSize(size)
{
top = 0;
pType = new T[size];
}
/*********************************************************
* Copy Constructor
*********************************************************/
template <class T>
Stack<T>::Stack(const Stack &rhs)
{
itsSize = rhs.GetSize();
pType = new T[itsSize];
for(int i = 0; i<itsSize; i++)
pType[i] = rhs[i];
}
/*********************************************************
* operator =
*********************************************************/
template <class T>
Stack<T>& Stack<T>::operator = (const Stack &rhs)
{
if(this == &rhs)
return *this;
delete [] pType;
itsSize = rhs.GetSize();
pType = new T[itsSize];
for(int i = 0; i<itsSize; i++)
pType[i] = rhs[i];
return *this;
}
/*********************************************************
* Member Function -- TOP
*********************************************************/
template <class T>
T const Stack<T>::TOP()
{
if(top == 0)
{
cout<<"ERROR: Stack is null!"<<endl;
return NULL;
}
return pType[top];
}
/*********************************************************
* Member Function -- PUSH
*********************************************************/
template <class T>
void Stack<T>::PUSH(T element)
{
if(top<itsSize){
top++;
pType[top] = element;
}
else
cout<<"ERROR: The stack is full!"<<endl;
}
/*********************************************************
* Member Function -- POP
*********************************************************/
/*template <class T>
void const Stack<T>::POP()
{
if(top != 0){
top--;
}
else
cout<<"ERROR: The stack is empty!"<<endl;
}*/