C 堆栈实现意外输出
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){}
我在您的代码中发现的一个问题是,您在节点的类中声明另一个a
变量
Node(int b){
//int a = b; when you define a new `a` variable, old one is ignored
a=b;
next = NULL;
}
所有私人成员均在类内定义,因此所有类都可以看到变量a
。但是,当您在子范围内声明一个新变量时,在此子镜头内忽略了一般范围中的a
变量
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 字符串比较中的意外输出
- 每次在 c++ 中输出不同(意外行为)
- 来自 decltype 的意外输出类型
- 字符数组到十六进制字符串的转换 - 意外输出
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用后序遍历递归的深度优先搜索会产生意外输出
- C++的意外输出
- 标准输出C++意外行为
- 贝金纳C++练习解决方案的意外输出
- 无效* 转换获得意外输出
- 以下程序的意外输出
- 意外输出:矢量矢量(功率集)
- 基本 int 数组提供意外输出
- 线程的意外输出
- 减法中的意外输出
- 带有左移操作员C 的意外输出
- C strncpy意外输出
- 意外输出..函数绑定在虚拟表中的发生方式
- 星号的意外输出