C++ 二叉树中的算子重载
我正在为我正在创建的二叉树函数编写各种运算符重载,规范要求重载以将一棵树复制到另一棵树C++ 二叉树中的算子重载,c++,tree,operator-overloading,binary-tree,C++,Tree,Operator Overloading,Binary Tree,我正在为我正在创建的二叉树函数编写各种运算符重载,规范要求重载以将一棵树复制到另一棵树 binary_tree& binary_tree::operator=(const binary_tree &other) { return binary_tree(); } 操作员工作的测试如下: int main(int argc, char **argv) { tree = new binary_tree(vector<int>{11, 5, 3, 7}); binary
binary_tree& binary_tree::operator=(const binary_tree &other)
{
return binary_tree();
}
操作员工作的测试如下:
int main(int argc, char **argv)
{
tree = new binary_tree(vector<int>{11, 5, 3, 7});
binary_tree temp = *tree;
temp.insert(12);
str = temp.inorder();
if (str != string("3 5 7 11 12") && temp.inorder() != tree->inorder())
cerr << "test failed (assignment operator)" << endl;
else
cout << "test passed (assignment operator)" << endl;
}
但是使用它们似乎没有任何用处。如果试图通过引用返回操作符的本地对象,则所有尝试都将失败
binary_tree& binary_tree::operator=(const binary_tree &other)
{
...
return binary_tree(); // <=== ouch: the reference will be invalid !
}
现在为了实现你的复制,你可以考虑重用你的二进制树::复制树。假设树中有一个node*根,它将类似于:
binary_tree& binary_tree::operator=(const binary_tree &other)
{
copyTree (root, other.root);
return *this;
}
让我们看看你试过的东西。只是说我试过很多东西,但都不管用;请替我写代码,恐怕这里很少有好的结果。一个二叉树类,不是函数;赋值运算符应返回对self的引用;我在=运算符中尝试了各种方法,但似乎都没有任何效果。当然,二叉树temp=*tree;它不是调用赋值运算符,而是调用复制构造函数。@blazs self是Python。你是说这个。这里也有很多内存泄漏。
binary_tree& binary_tree::operator=(const binary_tree &other)
{
... // make your copy here
return *this;
}
binary_tree& binary_tree::operator=(const binary_tree &other)
{
copyTree (root, other.root);
return *this;
}