print(); -6ren">
gpt4 book ai didi

c++ - 类指针失去成员?

转载 作者:太空宇宙 更新时间:2023-11-04 14:16:45 24 4
gpt4 key购买 nike

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

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();
}

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

最佳答案

你确定要写:

string mystring = node->print();

不是

string mystring = hello->print();

如果是的话,好像是'this' of

string mystring = node->print();

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

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

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

关于c++ - 类指针失去成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com