Sen*_*iri 1 c c++ stack pointers
我是一个相当有经验的C#程序员,并试图用一个创建Stack对象的C++应用程序来帮助一个朋友.自从我看到C++以来,我已经有超过13年的时间了,我正试着回忆起正确的方法.我花了一些时间再次加快了Header/CPP的区别,所以甚至可能存在问题.这是我的问题:
//Stack.h
#ifndef __STACK_INCLUDED__
#define __STACK_INCLUDED__
#include "Node.h"
class Stack
{
private:
/// Going to be the pointer to our top node
Node* m_topNode;
/// Running count of elements
int m_count;
public:
///Constructor
Stack();
///Allows us to retrieve the top value from the stack
/// and remove it from the stack
int Pop();
.
.
.
};
#endif
Run Code Online (Sandbox Code Playgroud)
以下是与标题匹配的CPP.我现在正在这里进行调试.我也完全符合条件,因为我不确定这是否会引起指针问题和参考文献丢失.
//Stack.cpp
#include "stdafx.h"
#include "Stack.h"
#include <iostream>
Stack::Stack(){
m_count = 0;
m_topNode = NULL;
}
void Stack::Push(int Value){
std::cout << "\nPushing Value: ";
std::cout << Value;
std::cout << "\n";
if ( Stack::m_topNode )
{
std::cout << "TopNode Value: ";
std::cout << Stack::m_topNode->data;
std::cout << "\n";
}
std::cout << "\n";
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
}
Run Code Online (Sandbox Code Playgroud)
节点类是一个非常简单的实体.只需要在两边存储一个值和指针.我知道我不需要在两个方向上跟踪堆栈,但我想将这个容易改为Queue或类似构造的东西.
//Node.h
#ifndef __NODE_INCLUDED__
#define __NODE_INCLUDED__
class Node
{
private:
public:
///Constructor allows us to specify all values.
/// In a stack I expect NextNode to be NULL
Node(int Value,Node* NextNode, Node* PreviousNode);
///Pointer to the next node
Node* Next;
///Pointer to the previous node
Node* Prev;
///Value to be stored
int data;
};
#endif
Run Code Online (Sandbox Code Playgroud)
非常简单的实现://Node.cpp #include"stdafx.h"#include"Node.h"
Node::Node(int Value, Node* NextNode, Node* PreviousNode){
data = Value;
Next = NextNode;
Prev = PreviousNode;
}
Run Code Online (Sandbox Code Playgroud)
我的主要目的是通过Push立即向堆栈发送2个值并查看值的打印内容:
#include "stdafx.h"
#include "Node.h"
#include "Stack.h"
using namespace std;
int main(){
Stack s = Stack();
for ( int i = 0; i < 2; i++ ){
s.Push(i * 10);
}
int blah;
cin >> blah; //Stall screen
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
Pushing Value: 0
<blank line>
Pushing Value: 10
TopNode Value: -858993460
Run Code Online (Sandbox Code Playgroud)
当我在调试器中点击Node newNode(Value,NULL,Stack :: m_topNode)时,我可以看到它跟踪当前节点中的正确值,但是m_topNode引用了一个非常奇怪的值.我希望很明显,我正在做一些愚蠢的事情,因为我不记得多年前这样做时这是多么棘手.感谢对我不正确礼仪的任何帮助/见解.
Node newNode(Value, NULL, Stack::m_topNode);
Stack::m_topNode = &newNode;
Stack::m_count++;
Run Code Online (Sandbox Code Playgroud)
这是你的问题.您在当前堆栈上分配新节点,然后将指针放入链接的节点列表中.一旦堆栈帧返回,此指针将无效,并且所有地狱中断都会丢失.;)
您需要使用new分配节点.
归档时间: |
|
查看次数: |
1506 次 |
最近记录: |