[英]Deep Copy Constructor for Abstract Member and Class Function Pointer in C++
这是一个作业问题。 有一个纯虚拟的构造函数,假定原始不为null
BST::BST(const BST& original) {
root = original.root;
if (root != nullptr)
{
root = new Node();
root->setValue( original.root->getValue() );
Node* subtree = root;
Node* temp = original.root;
while (temp != nullptr)
{
subtree = new Node();
subtree->setLeft(temp->getLeft());
temp = temp->getLeft();
subtree = subtree->getLeft();
}
temp = original.root;
while (temp != nullptr)
{
subtree = new Node();
subtree->setRight(temp->getRight());
temp = temp->getRight();
subtree = subtree->getLeft();
}
}
}
//克隆
BST::VIRTUALBinary* clone() {
return (new BST(*this)); }
//调用main
VIRTUALBinary* orig = new BST();
VIRTUALBinary* copy = new BST();
copy = orig;
//删除原始文件,希望将副本保留在main中
delete orig;
该副本似乎与原始函数具有相同的值,因为每次我删除原始副本时,副本都会自动删除。 任何帮助将不胜感激,非常感谢。
您仅在复制指针。
使用clone
方法:
VIRTUALBinary* copy = orig->clone()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.