C++ Stack 实现意外输出

C++ Stack implementation unexpected output

#include <iostream>

using namespace std;
/*Stack
last in first out algorithm
pop, push, print*/
class Node{
private:
    int a;
public:
    Node *next;
    Node(){
        next = NULL;
    };
    Node(int b){
        int a = b;
        next = NULL;
    }
    int getValue();
};

int Node::getValue(){
    return a;
}

class Stack{
    Node *top;
public:
    Node* pop();
    void push(int);
    Stack(){
        top=NULL;
    }
    void printStack();
}aStack;

//pushing onto the stack
void Stack::push(int z){
    //if top is not null create a temp link it to top then set point top to temp
    if (top != NULL){
        Node*temp = new Node(z);
        temp->next = top;
        top = temp;
    }
    else
        //else just set the new node as top;
        top = new Node(z);
        top->next = NULL;
}

Node* Stack::pop(){
    if (top == NULL){
        cout << "Stack is empty" << endl;
    }
    else
        //top = top->next;
        return top;
        //top = top->next;
}
//prints the stack
void Stack::printStack(){
    int count = 0;
    while(top!=NULL){
        count++;
        cout << count << ": " << (*top).getValue() << endl;
        top = top->next;
    }
}

int main(){
    aStack.push(5);
    aStack.printStack();
    //cout << aStack.pop()->getValue()<< endl;
    cin.get();
}

大家好,我正在复习我的数据结构。我无法弄清楚为什么在将数字 5 压入空堆栈并将其打印出来后得到输出 0。请给我一个提示关于我做错了什么,谢谢。

Node::Node 中,您正在隐藏成员变量 a,

int a = b;

替换为

a = b;

或更好,使用构造函数初始化列表

Node(int b): a(b), next(NULL){}

我在你的代码中发现的一个问题是你在节点

的 class 中声明了另一个 a 变量
Node(int b){
    //int a = b; when you define a new `a` variable, old one is ignored
    a=b;
    next = NULL;
}

所有私有成员都定义在class内,所以所有class都可以看到变量a。但是当你在子作用域中声明一个新变量时,一般作用域中的 a 变量在这个子作用域中被忽略