【发布时间】:2012-05-06 21:46:16
【问题描述】:
我有一棵二叉树,我正在搜索:
TreeNode<Vessel*>* node = this->tree_->search("PotatoFace");
string mystring = node->print();
当我运行它时,节点包含正确的数据,但是当我一输入就打印该数据时:
string TreeNode<T>::print()
{
return data_->toString();
}
'this'(应该是 'node' 并且与 '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();
}
仍然不完全确定如何解释它为什么不起作用,但这是一个范围问题,在二叉树类树节点之外丢失数据。取出所有返回节点的树函数,现在一切正常。
【问题讨论】:
-
发布定义。另外,您确实意识到
TreeNode<Vessel*>* node = new TreeNode<Vessel*>();没有用,因为您在下一行重新分配了node,还会导致内存泄漏? -
更正了,以前是这样设置的,但在尝试修复它时,我改变了它。
-
toString 是什么?另外,你为什么在你的类中保留指针而不是对象?
-
toString() 返回一个包含data_类所有成员的字符串,它是一个指针,因为我的树中有3级继承,所以它可以存储6种不同类型的容器。跨度>
-
Is TreeNode
* hello = this->tree_->search("PotatoFace");字符串 mystring = node->print();是在类的范围内执行还是在单独的范围内(例如 main 函数)执行?
标签: c++ pointers binary-tree dereference