C++ Stack 实现意外输出

标签 c++ pointers object stack

#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){}

关于C++ Stack 实现意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30292664/

相关文章:

c++ - 如何找到应该导出的符号

c++ - 操作系统开发。如何开始?

python - 方法可以在 Python 中有方法吗?

javascript - 如何在 React.js 中遍历来自 json 的对象数组

javascript - 如何让Joi具有非凡的值(value)?

c++ - 如何修复 Header with Namespaces 中常量的重定义错误?

c++ - libpng 1.4 系列有什么新东西吗?

objective-c - 为什么这个对象释放不正常,我应该释放它吗?

pointers - 为什么Fortran POINTER需要一个TARGET?

c++ - 指针,将参数传递给 main 和段错误