【发布时间】:2019-03-02 22:36:44
【问题描述】:
当我运行我的程序时,它会将数字完美地推入数组。但是当它弹出它们,然后打印它们时,我得到了垃圾号码。问题是否与我的主要功能有关? 或者我没有在我的 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");
}
【问题讨论】:
-
阅读how to debug small programs。编译所有警告和调试信息 (
g++ -Wall -Wextra -g)。顺便说一句,您的list名称令人困惑。最好使用arr或tab... 因为它不是 list