How can a derived C++ class clone itself via a base pointer?

后端 未结 6 735
旧巷少年郎
旧巷少年郎 2021-01-13 09:34

Here\'s what I\'m trying to do (this code doesn\'t work):

class Base
{
    virtual Base *clone() { return new Base(this); }
    virtual void ID() { printf(\"         


        
6条回答
  •  [愿得一人]
    2021-01-13 10:27

    Once all the compile errors are fixed, I ended up with this:

    #include 
    
    class Base
    {
      public:
        Base() {}
        Base(const Base&) {}
        virtual Base *clone() { return new Base(*this); }
        virtual void ID() { printf("BASE"); }
    };
    
    class Derived : public Base
    {
      public:
        Derived() {}
        Derived(const Derived&) {}
        virtual Base *clone() { return new Derived(*this); }
        virtual void ID() { printf("DERIVED"); }
    };
    
    
    int main()
    {
      Derived d;
      Base *bp = &d;
      Base *bp2 = bp->clone();
    
      bp2->ID();
    }
    

    Which gives you what you are looking for -- DERIVED.

提交回复
热议问题