类指针丢失成员
Class Pointer Losing Members?
我有一个二叉树,我正在搜索:
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* 类型的东西来纠正它,并且在我获得节点值后运行我想要的任何其他函数都是在二叉树类中完成的。这现在有效。谢谢你的帮助!
相关文章:
- 从成员指针到整个结构/类的强制转换
- OOP 中的单成员指针
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 共享 C++ 的数据成员指针
- 如何声明指向成员内容的成员指针m_pmd/m_pmf并访问它们?
- 从类C++外部调用指向成员方法的成员指针
- 结构成员指针是否自动初始化为零?
- 如何删除类内类类型的类成员指针
- 是否打印指向已定义 int 的成员指针
- 指向常量的成员指针
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- 无法删除在destructor中的成员指针的课程
- 删除对象而不调用成员指针的析构函数
- 当派生类的基类具有成员指针时,对其进行深层复制