[英]Pointer members of a class during assignment operator overloading
我正在尝试用c ++编写树构建程序。 (这是McCreight的后缀树),但是我对Node的赋值运算符重载有问题,特别是我类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打印正确的“叶子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这样的运行时),到目前为止,我在此处包含的代码是迄今为止给出最佳答案的代码,但是除非我找到一种了解父级的方法返回的节点中,我无法完成此操作! 当然,我可以将父母和祖父母作为单独的节点返回,但这并不有趣。 任何帮助都非常感谢。 谢谢!
使用std::shared_pointer
链接到节点,使用std::weak_pointer
链接。
您可以为您的类专门设置shared_pointer,以便将添加的簿记数据存储在节点本身中。 查看enable_shared_from_this<T>
。
您的分配运算符未正确实施。 尝试以下方法:
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;
}
在这种情况下,您可以完全省略运算符,并让编译器为您自动生成默认运算符,因为它将生成相同的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.