【问题标题】:Class Pointer Losing Members?类指针丢失成员?
【发布时间】: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&lt;Vessel*&gt;* node = new TreeNode&lt;Vessel*&gt;(); 没有用,因为您在下一行重新分配了node,还会导致内存泄漏?
  • 更正了,以前是这样设置的,但在尝试修复它时,我改变了它。
  • toString 是什么?另外,你为什么在你的类中保留指针而不是对象?
  • toString() 返回一个包含data_类所有成员的字符串,它是一个指针,因为我的树中有3级继承,所以它可以存储6种不同类型的容器。跨度>
  • Is TreeNode* hello = this->tree_->search("PotatoFace");字符串 mystring = node->print();是在类的范围内执行还是在单独的范围内(例如 main 函数)执行?

标签: c++ pointers binary-tree dereference


【解决方案1】:

你确定要写吗:

string mystring = node->print();

不是

string mystring = hello->print();

如果是的话,好像是“这个”的

string mystring = node->print();

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

  • 节点永远不会被初始化
  • 节点应该由search("something")设置但搜索返回null

如果您粘贴更多代码会非常有帮助。

【讨论】:

    【解决方案2】:

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

    通过确保二叉树类不返回 TreeNode* 类型的任何内容并在二叉树类中完成节点的值后运行我想要的任何其他函数来纠正它。这现在有效。 感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2019-12-28
      • 2018-03-24
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      相关资源
      最近更新 更多