类创建的堆栈
又出问题了.运行时出错,成员函数ADD第一次运行是没有出错的,增加第二个元素时出错,按运行顺序,错误好像出在析构函数,但却找不出有什么错。#include <iostream.h>
template <class T>
class Stack
{
public:
Stack();
~Stack(){delete []stack;}
Stack<T>& Add(const T& x);
void Output(ostream& out) const;
friend istream& operator>>(istream& in,Stack<T>& x);
private:
int top;
int MaxTop;
T *stack;
};
template <class T>
istream& operator>>(istream& in,Stack<T>& x)
{
T t;
cin>>t;
x.Add(t);
return in;
}
template <class T>
void Stack<T>::Output(ostream& out) const
{
int n=top+1;
for(int i=0;i<n;i++)
out<<stack[i]<<" ";
cout<<endl;
}
template <class T>
ostream& operator<<(ostream& out,Stack<T>& x)
{
x.Output(out);
return out;
}
template <class T>
Stack<T>::Stack()
{
MaxTop=0;
stack=new T[MaxTop+1];
top=-1;
}
template <class T>
Stack<T>& Stack<T>::Add(const T& x)
{
if((MaxTop-top)<1)
{
MaxTop=2*MaxTop+1;
T *t=new T[MaxTop];
for(int i=0;i<top+1;i++)
t[i]=stack[i];
delete []stack;
stack=t;
}
stack[++top]=x;
return *this;
}
void main()
{
Stack <int> s;
s.Add(2).Add(23);
cout<<"s:"<<s;
}