为什么弹出我的堆栈会返回垃圾而不是初始变量?

Why does popping off my stack return garbage instead of the initial variables?

本文关键字:变量 我的 堆栈 返回 为什么      更新时间:2023-10-16

当我运行我的程序时,它完美地将数字推入数组。但是当它弹出它们,然后打印它们时,我得到了垃圾数字。问题是否与我的主要功能有关? 还是我没有在 Stack 类中正确初始化我的数组?起初我的构造函数遇到了一些问题,但在进行一些调整后它似乎工作正常。

有什么突出的关于为什么我在运行脚本后收到垃圾号码

#include<iostream>
#include<cstdlib>
#ifndef MYSTACK_H
#define MYSTACK_H
#include<iostream>
#include<new>
using namespace std;

class MyStack
{
private:
int *list;
int top;
int max;
public:
MyStack(int m)
{
int max = m;
list = new int[max];
int top = -1;
}
~MyStack()
{
delete[] list;
}
int push(int);
int pop();
int peek(int &a) const;
};
int MyStack::push(int a)
{
if (top < max - 1)
{
top = top + 1;
list[top] = a;
return 0;
}
return -1;
}
int MyStack::pop()
{
if (top > -1)
{
top = top - 1;
return 0;
}
return -1;
}
int MyStack::peek(int &a) const
{
if (top > -1)
{
return(list[top]);
return 0;
}
return -1;
}
#endif
int main()
{
MyStack m(5);
for (int i = 0; i < 6; i++)
{
int x = 1 + rand() % 100;
cout << x << "t";
m.push(x);
}
cout << "n";
for (int i = 0; i < 6; i++)
{
int x;
m.peek(x);
cout << x << "t";
m.pop();
}
cout << "n";
system("pause>nul");
}

调用MyStack构造函数后未设置topmax,您正在创建局部变量,成员不受影响:

int max = m; // local 
list = new int[max];
int top = -1; // local

更改为

max = m;
list = new int[max];
top = -1;

>参数a永远不会在peek()函数中使用:

int MyStack::peek(int &a) const
{
if (top > -1)
{
return(list[top]); // you return the value instead of assigning it to "a"
return 0; // unreachable by the way
}
return -1;
}