简体   繁体   English

用于C ++中抽象成员和类函数指针的Deep Copy构造函数

[英]Deep Copy Constructor for Abstract Member and Class Function Pointer in C++

This is a homework question. 这是一个作业问题。 There is a pure virtual constructor involved, assume the original is not null 有一个纯虚拟的构造函数,假定原始不为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();
    }

}
}

//clone //克隆

  BST::VIRTUALBinary* clone() {
  return (new BST(*this)); }

//call to main //调用main

VIRTUALBinary* orig = new BST();
VIRTUALBinary* copy = new BST();
copy = orig;

//deleting original, hoping to keep copy in main //删除原始文件,希望将副本保留在main中

delete orig;

The copy seems to share the same value as the original function, because it deletes itself everytime I delete the original. 该副本似乎与原始函数具有相同的值,因为每次我删除原始副本时,副本都会自动删除。 Any help would be appreciated, much thanks. 任何帮助将不胜感激,非常感谢。

You are only copying the pointers. 您仅在复制指针。

Use your clone method: 使用clone方法:

VIRTUALBinary* copy = orig->clone()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM