c++ - 赋值运算符重载期间类的指针成员

标签 c++ pointers tree operator-overloading assignment-operator

我正在尝试用 C++ 编写树构建程序。 (这是 McCreight 的后缀树)但是我对节点的赋值运算符重载有问题,特别是我的类节点中的指针属性! 我的树构造方法中有这段代码不起作用(解释如下):

void ST::insert(int suffix, Node& leaf)
{
    .
    .
    .
    leaf=find_path(u.suffix);
    cout<<leaf.id<<" "<<leaf.parent->id<<'\n';
    .
    .
    .
}

Node ST::find_path(Node* node, int suffix)
{
    .
    .
    .
    cout<<leaf.parent->id<<'\n';
    return leaf;
}

find_path 中的 cout 打印出正确的父节点 ID,但是当将节点返回到 insert() 时,它的父节点丢失了。 cout in insert 打印出正确的“叶子 ID”,但它不知道“叶子的父 ID”。

我的 Node 类代码是这样的:

class Node
{
public:
    int id;
    Node* parent;
    vector <Node> children;
    vector <int> startPointer;
    Node* SL;
    int strDepth;
    Node()
    {
        parent=NULL;
        SL=NULL;
    }

Node& operator=(const Node node2)
{
    this->id=node2.id;
    if(this != &node2 && node2.parent!=NULL && node2.SL!=NULL)
    {
        *parent = *(node2.parent);
        parent = (node2.parent);
        *SL=*(node2.SL);
    }
    this->children=node2.children;
    this->startPointer=node2.startPointer;
    this->strDepth=node2.strDepth;
}

我已经尝试了很多方法来改变这个重载的运算符,但每种方法都会给出一些其他错误(通常是运行时,如 NullPointerException),我在此处包含的代码是迄今为止给出最佳答案的代码,但除非我找到一种方法知道返回节点的父节点我无法完成这个!当然我可以将 parent 和祖 parent 作为单独的节点返回,但这并不有趣。非常感谢任何帮助。谢谢!

最佳答案

使用 std::shared_pointer用于指向节点的链接,以及 std::weak_pointer用于反向链接。

您可以为您的类专门化 shared_pointer,以便添加的簿记数据存储在节点本身中。看enable_shared_from_this<T> .

关于c++ - 赋值运算符重载期间类的指针成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885235/

相关文章:

c++ - 自定义消息Dlg

pointers - 使用rust 的生活

c++ - 使用带有 char 变量的指针

c++ - 取消引用已分配特定内存地址的指针

r - 使用 R 中 'rpart' 包中的生存树来预测新的观察结果

r - 如何在 R 中绘制 CostSensitiveClassifier 树?

python - 具有与 Python 的过滤器和映射相同功能的 C++ 工具

c++ - 使用模板和基类实现灵活的数组成员

c++ - 指针传递和参数

java - 自下而上填充一棵树