c++ - 成员变量重置回 0

标签 c++ class

在运行测试时,类 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 的原因。)

还有:

  1. arr[count] = NULL; 没有意义。 NULL 应该用在指针上下文中,而不是整数上下文中。这甚至不能保证编译。

    那到底有什么意义呢?最初,您的数组在当前堆栈顶部上方包含垃圾。为什么你在执行完 pop 后突然想清理它?

  2. 并非所有pop() 返回值的控制路径。这本身就是未定义的行为。

  3. 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/

相关文章:

c++ - 更新/替换 `boost::hana::map` 中映射值的规范方法

c++ - grpc 找不到 protobuf 库

c++ - 模板化类是否继承传递给它们的类的成员? (特别是 std::vector)

java - Java/Gradle-从.class文件构建.jar文件

c++ - 删除非指针 vector 中的指针

c++ - 为什么 std::condition_variable 不能正常工作?总是在等待之前通知

c++ - 在 Visual Studio 2010 中调试由 C++ 程序调用的 Fortran dll

java - 为什么java的-verbose :class argument include jre inherent native classes?没有

java - 多个子类,如何实例化其中的任何一个?

c++ - C++ 类中的运算符