C ++ Stack实现意外输出

时间:2015-05-17 22:08:20

标签: 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。关于我做错了,请给我一个 HINT ,谢谢。

2 个答案:

答案 0 :(得分:4)

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

int a = b;

将其替换为

a = b;

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

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

答案 1 :(得分:1)

我在您的代码中发现的一个问题是,您在节点类中声明了另一个a变量

Node(int b){
    //int a = b; when you define a new `a` variable, old one is ignored
    a=b;
    next = NULL;
}

所有私有成员都在类中定义,因此所有类都可以看到变量a。但是当您在子范围中声明一个新变量时,在该子范围内忽略一般范围中的a变量