我为堆栈编写了C ++代码。我收到一个错误,即数组'a'尚未在push,pop和display函数的范围内声明。我试图删除私人,但问题仍然存在。我该如何解决这个问题?
我的代码:
#include<iostream>
using namespace std;
class stack
{
private:
int n;
int a[10];
int top;
public:
stack(int n);
void push(int x);
int pop();
void display();
};
stack::stack(int q)
{
n=q;
top=-1;
}
void stack::push(int x)
{
if(top==n-1)
cout<<"\nStack overflow\n";
else
a[++top]=x;
}
int stack::pop()
{
if(top==-1)
cout<<"\nStack is empty\n";
else
return (a[top--]);
}
void stack::display()
{
int i;
for(i=top;i>=0;i--)
cout<<a[i]<<endl;
}
int main()
{
int n;
cout<<"\nEnter the size of stack\n";
cin>>n;
stack st(n);
int i,x;
while(1)
{
cout<<"\nSelect option 1.Push 2.Pop 3.Display\n";
cin>>i;
switch(i)
{
case 1: cin>>x;
st.push(x);
break;
case 2: st.pop();
break;
case 3: st.display();
break;
}
}
return 0;
}