首页 > 解决方案 > 为什么将 r 值分配给数组下标内的变量

问题描述

我的推送功能有问题。数组下标(顶部)内的变量正在使用 r 值(项目)初始化。

  1. 当我使用 top=0 执行相同的操作时,它工作正常。

  2. 仅当 top=-1 时才会出现问题。

  3. 在第二次和第三次函数调用中,top 的值是按顺序递增的,而不是由 r-value(item) 初始化的

  4. 我每次都打印最高值以简化调试。

    class stack
    {
    
    int top;
    public:
        int arr[500];
    
        stack()
        {
            top=-1;
        }
    
        void push(int);
    
    };
    
    void stack::push(int item)
    {
    
    
    arr[top++]=item;
    cout<<"\n"<<item<<"pushed in stack";
    cout<<"\n top value is"<<top;
    
    }
    int main()
    {   
        stack s;
        s.push(12);
        s.push(19);
        s.push(31);
        return 0;
     }
    

我预计输出为“12 压入堆栈且顶部值 = 0,但实际输出为 12 压入堆栈且顶部值为 12

标签: arraysc++11post-increment

解决方案


推荐阅读