2012-05-06 63 views
1

我有一个二叉树,我正在寻找:班级指针失去成员?

TreeNode<Vessel*>* node = this->tree_->search("PotatoFace"); 
string mystring = node->print(); 

当我运行它,节点包含正确的数据,但是当我去打印,只要我输入数据:

string TreeNode<T>::print() 
{ 
return data_->toString(); 
} 

'this'(应该是“节点”并且与'node'具有相同的内存地址)将其所有数据成员包括Vessel *设置为null。

任何想法?

谢谢!

全树节点:

#pragma once 
#include <cstring> 
#include <fstream> 
#include <iostream> 
using namespace std; 

template <class T> 
class TreeNode 
{ 
private: 
TreeNode<T>* greaterNode_; 
TreeNode<T>* lessNode_; 
TreeNode<T>* parentNode_; 
TreeNode<T>* getLowest_(); 
T data_; 


public: 
TreeNode(); 
TreeNode(T data); 
void add(T data); 
bool operator==(const string &rhs); 
TreeNode* search(T data); 
void seqSearch(string data, TreeNode<T>* node); 
void del(TreeNode<T>* root); 
void toFile(ofstream& BSTFile); 
TreeNode* compare(int sig[4]); 
TreeNode* getRoot(); 
TreeNode* forward(TreeNode<T>* node); 

string print(); 
}; 


template <class T> 
TreeNode<T>::TreeNode(T data) 
{ 
data_ = data; 
greaterNode_ = lessNode_ = parentNode_= NULL; 

} 
template <class T> 
TreeNode<T>::TreeNode() 
{ 
} 

template <class T> 
void TreeNode<T>::seqSearch(string data, TreeNode<T>* node) 
{ 
if(*data_ == data) 
{ 
    *node = this->data_; 
} 
if(this->lessNode_) 
{ 
    this->lessNode_->seqSearch(data, node); 
} 
if(this->greaterNode_) 
{ 
    this->greaterNode_->seqSearch(data, node); 
} 
} 

template <class T> 
string TreeNode<T>::print() 
{ 
return data_->toString(); 
} 

还没完全知道如何解释为什么它不工作,但它是一个范围的问题,外面的二叉树分类节点丢失的数据。取出返回节点的所有树函数,现在所有的工作都可以使用。

+4

发布定义。另外,你知道'TreeNode * node = new TreeNode ();'是无用的,因为你在下一行重新分配'node',并且导致内存泄漏? –

+0

纠正了这个问题,之前它是这样设置的,但在尝试修复它时,我改变了它。 – lex

+0

什么是toString?另外,你为什么要在你的课堂中保持指针而不是对象? –

回答

0

仍然不完全确定如何解释为什么它不起作用,但它是一个范围问题,在二叉树类树节点之外丢失数据。

通过确保Binary Tree类不返回任何类型的TreeNode *并运行任何我想要的其他函数,只要我已经在二叉树类中完成了该节点的值,就可以纠正它。这现在起作用。 谢谢你的帮助!

0

你确定你想写:

string mystring = node->print(); 

string mystring = hello->print(); 

如果是,它看起来像 '这' 的

string mystring = node->print(); 

为空(null节点)。这可能有几个原因:

  • 节点永远不会被初始化
  • 节点应该被搜索设置(“东西”),但搜索返回null

如果粘贴更多的代码这将是非常有益的。