模拟栈的小程序,错哪了?

来源:百度知道 编辑:UC知道 时间:2024/06/01 11:42:35
#include <iostream.h>
class Sstrack {
static int num;
int* s;
int sz;
public:
void set(int size);
void push(int x);
void pop();
};
int Sstrack::num=0;
void Sstrack::set(int size){
sz=size;
if (size<0){cerr<<"bad"<<endl; exit(1);}
new s=int[sz];
}
void Sstrack::push(int x){
s[num]=x;
if (num>9) cerr<<"out of range"<<endl;
else num++;
}
void Sstrack::pop(){
cout<<s[num-1]<<endl;
if (num<0) cerr<<"out of range";
else num--;
}

int main(){
Sstrack a;
a.set(10);
a.push(12);
a.push(14);
a.push(15);
a.push(16);
a.push(17);
a.push(18);
a.push(12);
a.push(14);
a.push(15);
a.push(16);
a.push(17);
a.push(18);
a.pop();
a.pop();
a.pop();
a.pop();

#include <iostream.h>
#include <stdlib.h>

class Sstrack {
static int num;
int* s;
int sz;

public:
void set(int size);
void push(int x);
void pop();
};

int Sstrack::num = 0;
void Sstrack::set(int size)
{
sz = size;
if (size<0)
{
cerr << "bad" << endl;
exit(1);
}
s = new int[sz];
}
void Sstrack::push(int x)
{
if (num > sz-1) cerr << "out of range" << endl;
else
{
s[num] = x;
num++;
}
}
void Sstrack::pop()
{
if(num < 1) cerr<<"out of range";
else
{
cout << s[num-1] << endl;
num--;
}
}

int main(){
Sstrack a;
a.set(10);
a.push(12);
a.push(14);
a.push(15);
a.push(16);
a.push(1