【发布时间】:2013-11-22 06:04:35
【问题描述】:
我有一些关于二叉搜索树 (BSTreeBag) 的代码行,但我不太明白。
“operator +=(const BSTreeBag& addend)”要求将 addend 中的内容插入到我们拥有的当前树中。如果我们拥有的当前树与“addend”相同,我们需要将树加倍(以复制树中的所有项目)
这是我的代码
template <class ItemType>
void BSTreeBag<ItemType>::operator +=(const BSTreeBag& addend)
{
if(this==&addend)//This works
{
binary_tree_node<ItemType>* addroot_ptr=root_ptr;//create a pointer
//that points to the current tree
insert_all(addroot_ptr);//This is a helper function that insert
//every item of the addend into the current tree. It works fine.
}
else
{
insert_all(addend.root_ptr);
}
}
只要不进行自赋值,代码行就可以完美运行。它总是停在这条线上
insert_all(addroot_ptr);
没有提供有关分段错误或其他问题的任何信息。有人可以解释发生了什么吗?
【问题讨论】:
-
您知道您的操作员被声明(和定义)错误吗?它应该返回对对象实例的引用(例如
*this)。 -
另外,为什么要创建一个临时指针而不是直接传递
root_ptr? -
我想如果我使用root_ptr,它指向的对象会改变。 root_ptr 是指向根的指针。它不应该改变。
-
另外我认为这个函数是无效的,它不需要返回任何东西。就像我说的那样,问题出在“如果”部分,其他一切正常。
-
他们不是在做同样的事情,自我分配与否?我认为 insert_all() 有问题。
标签: c++ data-structures tree