gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:58:16 25 4
gpt4 key购买 nike

我正在尝试用 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/

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