类指针丢失成员

Class Pointer Losing Members?

本文关键字:成员 指针      更新时间:2023-10-16

我有一个二叉树,我正在搜索:

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

当我运行它时,节点包含正确的数据,但是当我输入后立即打印该数据时:

string TreeNode<T>::print()
{
return data_->toString();
}
"this"(应该是"节点",并且具有

与"节点"相同的内存地址)将其所有数据成员(包括 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();
}

仍然不完全确定如何解释为什么它不起作用,但这是一个范围问题,在二叉树类之外的树节点丢失了数据。取出所有返回节点的树函数,现在一切正常。

你确定要写:

string mystring = node->print();

string mystring = hello->print();

如果是,它似乎是"这个"

string mystring = node->print();
为空

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

  • 节点永远不会初始化
  • 节点应该由搜索("某物")设置,但搜索返回空

如果您粘贴更多代码,这将非常有帮助。

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

通过确保二叉树类不返回任何 TreeNode* 类型的东西来纠正它,并且在我获得节点值后运行我想要的任何其他函数都是在二叉树类中完成的。这现在有效。谢谢你的帮助!