在运行测试时,类 stack1 中的计数变量在使用其 pop 函数时会重置回 0。然而奇怪的是,在推循环期间,计数按预期增加,但当弹出发生时,计数被重置回 0 并从那里减去负数。我忘记了什么吗?
#include <iostream>
using namespace std;
class TheStack
{
public:
TheStack();
void push(int);
int pop();
bool isEmpty();
private:
const int MaxSize = 10;
int arr[10];
int count;
};
TheStack::TheStack()
{
count = 0;
}
void TheStack::push(int userInput)
{
if (count >= MaxSize)
{
cout << "Stack is full." << endl;
}
else
{
arr[count] = userInput;
count+=1;
}
}
int TheStack::pop()
{
if (isEmpty())
{
cout << "Stack is empty." << endl;
}
else
{
int temp = arr[count];
arr[count] = NULL;
count-=1;
return temp;
}
}
bool TheStack::isEmpty()
{
if (count == 0)
{
return true;
}
else
{
return false;
}
}
int main()
{
TheStack stack1;
if (stack1.isEmpty())
{
cout << "isEmpty() works" << endl;
}
stack1.pop();
for (int i = 0; i < 10; i++)
{
stack1.push(i);
}
stack1.push(0);
stack1.pop();
stack1.pop();
stack1.pop();
stack1.pop();
system("pause");
}
最佳答案
当您执行push
时,您首先将数据保存到数组中,然后递增count
。这意味着为了正确地执行 pop
你需要反向工作:first decrement count
and only then从数组中读取数据。
但是在代码中你是在倒退。当堆栈已满时,count
处于最大值(在您的情况下为 10
),并且您的 arr[count] = NULL;
写入超出数组边界。这会导致未定义的行为,特别是会破坏您的 count
值。 (这就是它突然变成 0
的原因。)
还有:
arr[count] = NULL;
没有意义。NULL
应该用在指针上下文中,而不是整数上下文中。这甚至不能保证编译。那到底有什么意义呢?最初,您的数组在当前堆栈顶部上方包含垃圾。为什么你在执行完
pop
后突然想清理它?并非所有
pop()
返回值的控制路径。这本身就是未定义的行为。const int MaxSize = 10;
在类定义中是一个 C++11 特性。由于您已经在使用 C++11,因此您可以对count
执行相同的操作。只需在类定义中执行int count = 0;
,您就不必显式编写构造函数。尽管在您的实现中
MaxSize
作为static const
类成员更有意义。在这种情况下,您还可以将数组声明为int arr[MaxSize];
。
关于c++ - 成员变量重置回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837459/