简体   繁体   English

C++ 类成员:为什么类成员从第二次访问返回不同的值?

[英]C++ class member: Why does class member return different value from second access?

I'm new to C++, and wrote NumberStack class in stack.cpp as follows, but the result is different from what I expected, So I need your help:我是 C++ 新手,在 stack.cpp 中写了 NumberStack 类如下,但结果和我预期的不一样,所以我需要你的帮助:

#include <iostream>

class LinkedListNode {
    public:
        int value;
        LinkedListNode* next;

        LinkedListNode(int initialValue) {
            value = initialValue;
        }
};

class NumberStack {
    public:
        LinkedListNode* head;

        NumberStack(int initialValue) {
            LinkedListNode node(initialValue);
            node.next = NULL;
            head = &node;
        }

        void push(int initialValue) {
            LinkedListNode node(initialValue);
            node.next = head;
            head = &node;
        }

        int top() {
            return head->value;
        }
    private:
};

int main() {
    NumberStack myStack(6);
    myStack.push(2);
    myStack.push(5);

    std::cout << myStack.top() << "\n";
    std::cout << myStack.top() << "\n";
    std::cout << myStack.top() << "\n";

    return 0;
}

When executing this file, I got output like this:执行此文件时,我得到如下输出:

$ g++ stack.cpp
$ ./a.out
5
45264732
45264732

I expected output would be like this.我预计输出会是这样。

5
5
5

So what caused this?那么是什么原因造成的呢? I'm using MacOS Big Sur我正在使用 MacOS Big Sur

There are three changes that you need to make:您需要进行三项更改:

  • Initialize node's `next' in the constructor在构造函数中初始化节点的“next”
  • Initialize head to nullptrhead初始化为nullptr
  • Allocate nodes dynamically动态分配节点

Here is how:方法如下:

LinkedListNode(int v, LinkedListNode* n = nullptr): value(v), next(n) {}

Then call然后打电话

head = new LinkedListNode(initialValue, head);

I would also give NumberStack a default constructor, rather than a constructor that takes the initial value.我还会给NumberStack一个默认构造函数,而不是一个接受初始值的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM