C++模板類的前置宣告
template<typename T>
class LinkedStack;
template<typename T>
class Node
{
friend class LinkedStack<T>;
private:
T data;
Node<T> *link;
};
template<typename T>
class LinkedStack
{
public:
LinkedStack(){ top=0;}
~LinkedStack();
bool IsEmpty()const
{return top==0;}
bool IsFull()const;
T Top()const;
LinkedStack<T>& Add(const T& x);
LinkedStack<T>& Delete(T& x);
private:
Node<T> *top;
};
template<typename T>
LinkedStack<T>::~LinkedStack()
{
Node<T>* next;
while(top)
{
next=top->link;
delete top;
top=next;
}
}
template<typename T>
bool LinkedStack<T>::IsFull()const
{
try
{
Node<T>* p=new Node<T>;
delete p;
return false;
}
//catch(NoMem){return true;}
catch(){}
}
template<typename T>
T LinkedStack<T>::Top() const
{
//if(IsEmpty())throw OutOfBounds();
if(IsEmpty())exit(0);
else
return top->data;
}
template<typename T>
LinkedStack<T>& LinkedStack<T>::Add(const T &x)
{
Node<T>* p=new Node<T>;
p->data=x;
p->link=top;
top=p;
return *this;
}
template<typename T>
LinkedStack<T>& LinkedStack<T>::Delete(T &x)
{
if(IsEmpty())throw OutOfBounds();
x=top->data;
Node<T>* p=top;
top=top->link;
delete p;
return *this;
}