这是我的第一个数据结构程序。我正在实现一个使用数组的push,pop和initialize函数的简单堆栈。我得到一个无限循环作为输出。你能告诉我这是为什么吗?无限循环栈实现C++
#include<iostream>
using namespace std;
# define SIZE 6
class stack{
public:
void init();
void push(int i);
int pop();
int top;
int stck[SIZE];//bydefault private
};
void stack::init()
{
top=0;
return;
}
void stack::push(int i)
{
if(top==SIZE)
{
cout<<"stack is full";
return;
}
else
{
top=top+1;
stck[top]= i;
return;
}
}
int stack::pop()
{
if(top==0)
{
cout<<"stack is empty. \n";
return 0;
}
else
{
top = top-1;
return(stck[top-1]);
}
}
int main()
{
stack stack1;
stack1.init();
int a;
int m;
while(a!=4)
{
cout<<"1. push 2. pop 3.display 4.exit .\n";
cin>>a;
if(a==1){
cout<< "enter value";
cin>>m;
stack1.push(m);
}
if(a==2)
{
cout<<"popped"<< stack1.pop();
}
if(a==3)
{
for(int k=0; k<=stack1.top;k++)
{
cout<<stack1.stck[k];
}
}
}
}
为什么你认为有无限循环? – Maroun
如果您编写自己的类,则应该使用私有字段和构造函数。 – tgmath
如果你去公众场合,你就不会穿脏兮兮的衬衫,所以请在公共场合介绍格式良好的代码。不鼓励使用宏的常量,而是使用'const'变量。另外,不鼓励使用'using namespace std;',否则会导致名称冲突。 – Flovdis