简体   繁体   English

C ++通过抽象基类在未知派生类上调用复制构造函数

[英]C++ Calling a copy constructor on an unknown derived class through an abstract base class

I'm making a tree that has several different node types: a binary node, a unary node, and a terminal node. 我正在创建一个具有多种不同节点类型的树:二进制节点,一元节点和终端节点。 I've got an ABC that all the nodes inherit from. 我有一个所有节点继承的ABC。 I'm trying to write a recursive copy constructor for the tree like so: 我正在尝试为树编写递归复制构造函数,如下所示:

class gpnode
{
public:
  gpnode() {};
  virtual ~gpnode() {};
  gpnode(const gpnode& src) {};

  gpnode* parent;
}

class bnode:gpnode
{
public:
  bnode() {//stuff};
  ~bnode() {//recursive delete};

  bnode(const bnode& src)
  {
    lnode = gpnode(src.lnode);
    rnode = gpnode(src.rnode);

    lnode->parent = this;
    rnode->parent = this;
  }

  gpnode* lnode;
  gpnode* rnode;
}

class unode:gpnode
{
public:
  unode() {//stuff};
  ~unode() {//recursive delete};

  unode(const unode& src)
  {
    node = gpnode(src.node);

    node->parent = this;
  }

  gpnode* node;
}

My problem is that I can't do 我的问题是我做不到

node = gpnode(src.node);

because gpnode is a virtual class. 因为gpnode是一个虚拟类。 I could do 我可以

node = unode(src.node);

but that doesn't work when the child of a unode is a bnode. 但是当unode的子节点是bnode时,这不起作用。 How do I get it to intelligently call the copy constructor I need it to? 如何让它智能地调用我需要它的复制构造函数?

You need to implement cloning. 您需要实现克隆。

   class base
   {
   public:
       virtual base* clone() const = 0;
   }

   class derived : public base
   {
   public:
       derived(){}; // default ctor
       derived(const derived&){}; // copy ctor

       virtual derived* clone() const { return new derived(*this); };
   };

Etceteras Etceteras

To do this you have to provide a clone -method for your objects, that returns a pointer of the appropriate type. 为此,您必须为对象提供clone -method,它返回适当类型的指针。 If all your classes have copy-constructors, that is as simple as that: 如果你的所有类都有copy-constructors,那就简单了:

node* clone() const {
    return new node(*this);
}

Where node is the class you are writing the clone -method for. 其中node是您正在为其编写clone -method的类。 You would of course have to declare that method in your base-class: 您当然必须在基类中声明该方法:

virtual gpnode* clone() const = 0;

使用虚拟构造函数

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

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