赋值运算符重载期间类的指针成员 我试图在C++中编写一个树构造程序。(这是McCreight的后缀树)但我对节点的赋值运算符重载有问题,特别是我的类节点中的指针属性! 我的树构造方法中包含此代码,但该代码不起作用(解释如下): void ST::insert(int后缀、节点和叶) { . . . 叶=查找路径(u后缀); 不能

赋值运算符重载期间类的指针成员 我试图在C++中编写一个树构造程序。(这是McCreight的后缀树)但我对节点的赋值运算符重载有问题,特别是我的类节点中的指针属性! 我的树构造方法中包含此代码,但该代码不起作用(解释如下): void ST::insert(int后缀、节点和叶) { . . . 叶=查找路径(u后缀); 不能,c++,pointers,tree,operator-overloading,assignment-operator,C++,Pointers,Tree,Operator Overloading,Assignment Operator,使用std::shared_pointer链接到节点,使用std::weak_pointer反向链接 您可以为您的类专门指定共享\u指针,以便添加的簿记数据存储在节点本身中。请查看enable\u shared\u from\u this您的赋值运算符未正确实现。请改为尝试以下操作: Node& operator=(const Node &node2) { if(this != &node2) { this->id=node2.id;

使用
std::shared_pointer
链接到节点,使用
std::weak_pointer
反向链接


您可以为您的类专门指定共享\u指针,以便添加的簿记数据存储在节点本身中。请查看
enable\u shared\u from\u this

您的赋值运算符未正确实现。请改为尝试以下操作:

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

在这种情况下,您可以完全省略该运算符,让编译器自动为您生成一个默认运算符,因为它将生成相同的代码。

您的代码有许多问题:首先,assignment运算符(除非您执行类似复制和交换习惯用法的操作)必须通过常量引用而不是值获取其参数。第二:您已经打破了三条规则:您应该实现一个自定义的复制ctor,a(正确)assigment运算符和析构函数。谢谢!但是如果我不打算在代码中使用该构造函数,您介意告诉我为什么需要复制构造函数吗?重载=运算符不会做同样的事情吗?(我有析构函数,但我没有在这里复制所有代码!)我复制了这个构造函数只是为了显示每个节点的父指针都是由NULL初始化的,所以它不会导致错误!谢谢。谢谢。我(再次)尝试了这个方法,但是find_path()中的cout给出了8作为父id,insert()中的cout给出了8给出5696520!这很聪明,也很有帮助!非常感谢!我已经更改了指针,正在尝试调试!我根本不知道共享和弱PTR。
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;
}
Node& operator=(const Node &node2)
{
    if(this != &node2)
    {
        this->id=node2.id;
        this->parent = node2.parent;
        SL=node2.SL;
        this->children=node2.children;
        this->startPointer=node2.startPointer;
        this->strDepth=node2.strDepth;
    }
    return *this;
}