Polymorphic copy-constructor with type conversion

后端 未结 4 1616
遇见更好的自我
遇见更好的自我 2021-01-26 11:18

I need to copy-construct an object simultaneously changing it\'s type to another class being a member of the same class-hierarchy. I\'ve read about polymorphic copy-constructors

4条回答
  •  长发绾君心
    2021-01-26 11:40

    If you only have 2 child classes, then the easiest way is to create a conversion constructor:

    class Child2: public Base
    {
    public: 
        Child2(Child1 const& child)
        {
                p_int = new int (*child.p_int);
                a = child.a + 1;        
        }
    }; 
    
    c2 = new Child2(*c1); 
    

    If you have several Child classes, and you need to create a Child2 from any of them, then you could do something like this:

    class Base
    {
    public: 
        void CopyFrom(Base* base)
        {
                p_int = new int (*base.p_int);
                a = base.a + 1;     
        }
    }; 
    
    class ChildX: public Base
    {
    public: 
        static ChildX* CreateFrom(Base* base)
        {
            ChildX ch = new ChildX(); 
            ch->CopyFrom(base); 
            return ch; 
        }
    }; 
    
    c2 = Child2::CreateFrom(c1); 
    

提交回复
热议问题