注册 登录
编程论坛 C++教室

简单栈的操作

bill8888 发布于 2007-03-31 15:05, 851 次点击
#include<iostream>
#include<conio.h>
using namespace std;
class Stack {
int *base,*top;
public:
void initstack(Stack s){
s.base=new int[10];
if(! s.base) exit(0);
s.top=s.base=0;
}
void push(Stack p,int n){
if(p.top-p.base>=10) cout<<"栈溢出!"<<endl;
else
{ *p.top++=n;
cout<<*(p.top--);}
}
void pop(Stack s){
if(s.top==s.base) cout<<"空栈"<<endl;
else {int e= * --s.top; cout<<"栈顶元素为:"<<e<<endl;}
}
};
int main()
{
Stack s;
s.initstack(s);
s.push(s,10);
s.push(s,12);
s.push(s,14);
s.pop(s);
getche();
}
内存不可读,是哪儿出了问题了,看了好办天没看出什么东西来,请大家帮忙~~
6 回复
#2
song42007-03-31 16:26
可以运行啊
DEV
#3
bill88882007-03-31 16:58
不是吧,我用的也是DEV C++啊,但我就不能,就是出现内存不能读的错误
#4
bill88882007-03-31 17:01
编译没得问题,就是一运行就出现内存不可读的问题,郁闷得很啊/////
我担心是不是我在建立空栈的时候分配内存地址的时候出了什么问题而导致内存不可读
#5
yuyunliuhen2007-03-31 18:25

<1>function should return a value;
<2>local variable 's' used without having been initialized;

#6
游乐园2007-03-31 19:57

这样试试吧 ...注意指针


#include<iostream>
using namespace std;


class Stack {
      int *base,*top;
      public:
                  Stack()
      {
                  base=new int[10];
                  if(!base)  exit(0);
                  top=base;
                  }
             void push(int n){
                  if(top-base>=10) cout<<\"栈溢出!\"<<endl;
                  else
                    {  *top++=n;
                     cout<<*(top-1)<<endl;
                    }
                  }
             void pop(){
                  if(top==base)  cout<<\"空栈\"<<endl;
                  else   {int e= * --top;  cout<<\"栈顶元素为:\"<<e<<endl;}
                  }
    ~Stack() {delete []base;}
};
int main()
{
    Stack s;
    s.push(10);
    s.push(12);
    s.push(14);
    s.pop();


return 0;
}

#7
bill88882007-03-31 21:53
谢谢大家了哈
我就觉得应该是我的内存空间没有处理好
1