0

当我使用构造函数定义运行以下程序时,执行最后一个弹出函数后输出为-1。

#define SIZE 100
class stack
{
private:
    int tos;
    int arr[SIZE];
public:
    stack(){tos=0;}
    int push(int);
    int pop();
};

int stack::push(int i)
{
    if(tos==SIZE)
        {cout<<"stack is full\n";}
        arr[tos]=i;
        tos++;
        return 0;
}
int stack::pop ()
{
    if(tos==0)
        {cout<<"stack is empty\n";}
        tos--;
        return arr[tos];
}

int main()
{
    stack stack1;
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);
    cout<<stack1.pop();
    cout<<stack1.pop();
    cout<<stack1.pop();
    cout<<stack1.pop();
    return 0;
}

但是当我尝试使用静态初始化运行时,同一个程序会给出垃圾值。为什么?

#define SIZE 100
class stack
{
    private:
        static int tos;
        int arr[SIZE];
    public:
        int push(int);
        int pop();
};

int stack :: tos = 0;
int stack::push(int i)
{
    if(tos==SIZE)
    {cout<<"stack is full\n";}
    arr[tos]=i;
    tos++;
    return 0;
}
int stack::pop ()
{
    if(tos==0)
    {cout<<"stack is empty\n";}
    tos--;
    return arr[tos];
}

int main()
{
    stack stack1;
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);
    cout<<stack1.pop();
    cout<<stack1.pop();
    cout<<stack1.pop();
    cout<<stack1.pop();
    return 0;
}
4

3 回答 3

1

您的两个程序都有相同的错误:

int stack::pop ()
{
    if(tos==0)
    {cout<<"stack is empty\n";}
    tos--;
    return arr[tos];
}

你试图让一个元素超出数组的范围。这会导致未定义的行为。功能上也是一样push

于 2013-09-20T09:52:35.650 回答
1

这是因为未定义的行为。当你 push 或 pop 时,你检查它是否正常,但即使它不是,也要继续操作。

pop因此,当您推送 3 次和弹出 4 次时,您将在函数中使用负索引来索引您的数组。

于 2013-09-20T09:51:36.123 回答
0

推送和弹出功能应更改为,

    #define SUCCESS 0
    #define FAILURE 1

    stack::stack(){tos=-1;}

    int stack::push(int i)
    {
        if(tos==SIZE)
        {
          cout<<"stack is full\n";
          return FAILURE;
        }
        else {
           arr[++tos]=i;
        }
        return SUCCESS;
    }

    int stack::pop ()
    {
       if(tos==-1)
       {
          cout<<"stack is empty\n";
          throw "Stack is Empty"; //Throw the exception, handle the exception in main
       }
       else 
       {
          return arr[tos--];
       }
    }
于 2013-09-20T10:23:05.267 回答