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

时间:2014-04-05 18:48:39

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

我试图用c ++编写树构造程序。 (它是McCreight的后缀树)但是我对节点的赋值运算符重载有问题,特别是我的类Node中的指针属性! 我的树构造方法中的代码不起作用(如下所述):

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打印正确的&#34;叶ID&#34;但它并不知道&#34;叶子的父母身份&#34;。

我的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),这里包含的代码是迄今为止给出最佳答案的代码,但除非我找到一种方法知道返回节点的父节点,我无法完成此操作!当然,我可以将父母和祖父母作为单独的节点返回,但这并不有趣。任何帮助都非常感谢。谢谢!

2 个答案:

答案 0 :(得分:1)

使用std::shared_pointer表示节点链接,std::weak_pointer表示反向链接。

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

答案 1 :(得分:0)

您的赋值运算符未正确实现。试试这个:

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

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

相关问题