栈的基本操作,vc编译通过,运行出现问题,调试发现输出栈元素时出现access violation,为什么出现这种情况?
#include<iostream>#include<stdlib.h>
#include<assert.h>
using namespace std;
class SeqStack;
ostream &operator<<(ostream &os,SeqStack &s);
const int maxSize=50;
const int stackIncreament=20;
class SeqStack
{
public:
SeqStack(int sz=50);
~SeqStack(){delete[] elements;}
void Push(const int &x);
bool IsFull()const{return (top==-1)?true:false;}
friend ostream &operator<<(ostream &os,SeqStack &s);
private:
int *elements;
int top;
int maxSize;
void overflowProcess();
};
//构造函数
SeqStack::SeqStack(int sz):top(-1),maxSize(sz)
{
elements=new int[maxSize];
assert(elements!=NULL);
}
//新元素x进栈
void SeqStack::Push(const int &x)
{
if(IsFull()==true)
overflowProcess();
elements[++top]=x;
}
//扩充栈的存储空间
void SeqStack::overflowProcess()
{
int *newArray=new int[maxSize+stackIncreament];
if(newArray==NULL){cerr<<"存储分配失败!"<<endl;exit(1);}
for(int i=0;i<top;i++)
newArray[i]=elements[i];
maxSize=maxSize+stackIncreament;
delete []elements;
}
//输出栈中元素的操作
ostream& operator<<(ostream& os,SeqStack& s)
{
os<<"top="<<s.top<<endl;
for(int i=0;i<=s.top;i++)
os<<i<<":"<<s.elements[i]<<endl;
return os;
}
int main()
{
int n;
cout<<"请输入栈的元素(以0结束):";
cin>>n;
SeqStack test;
while(n!=-111)
{
test.Push(n);
cin>>n;
}
cout<<test;
return 0;
}