Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

inheritance - 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. 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. I could do

node = unode(src.node);

but that doesn't work when the child of a unode is a bnode. How do I get it to intelligently call the copy constructor I need it to?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...