【问题标题】:Polymorphic copy-constructor with type conversion具有类型转换的多态复制构造函数
【发布时间】:2011-10-14 08:54:44
【问题描述】:

我需要复制构造一个对象,同时将其类型更改为另一个类,该类是同一类层次结构的成员。我已经阅读了多态复制构造函数,并且(希望)理解它背后的想法。然而,我仍然不知道这种模式是否适用于我的情况,如果适用,如何实现它。我认为最好在示例中展示我需要的内容。

有一个Base 类和两个子类Child1 和Child2。我需要基于Child1 创建一个Child2 类型的对象,即。最重要的是,我需要将p_int 指向的对象从Child1 复制到Child2。我写了一个简单的程序来说明它:

#include <iostream>
using namespace std;

class Base {
public:
    Base() { p_int = new int; *p_int = 0; }
    ~Base() { delete p_int; }
    virtual Base* clone() const = 0;

    void setpInt(int val) { *p_int = val; }
    void setInt(int val) { a = val; }
    virtual void print() {
        cout << "Base: ";
        cout << (long)p_int << ":" << *p_int << " " << a << endl;
    }
protected:
    int* p_int;
    int a;
};

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

    Base* clone() const { return new Child1(*this); }

    void print() {
        cout << "Child1: ";
        cout << (long)p_int << ":" << *p_int << " " << a << endl;
    }
};

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

    Base* clone() const { return new Child2(*this); }

    void print() {
        cout << "Child2: ";
        cout << (long)p_int << ":" << *p_int << " " << a << endl;
    }
};

int main() {
    Child1* c1 = new Child1();
    Child2* c2;

    c1->setpInt(4);
    c1->print();

    c2 = (Child2*)c1->clone();
    c2->print();
}

不幸的是,结果如下,即。没有类型转换:

Child1: 162611224:4 0
Child1: 162611272:4 1

我究竟需要实现什么才能实现我的需要?我开始认为我需要实现一种类型转换机制而不是多态复制构造函数,但我已经很困惑了。

编辑:要求跟进here

【问题讨论】:

  • 您的代码会产生内存泄漏:在派生类的复制构造函数中,您分配新内存并将其地址分配给 p_int,而不会释放先前在 Base 的默认构造函数中分配的内存。跨度>
  • 是吗?我认为虚拟 Base 类的析构函数会释放为 Child1.p_int 保留的内存,不是吗?
  • 是的,虚拟析构函数将释放p_int指向的内存,但是你分配了两次(一次在Base的构造函数中,一次在Child的构造函数中)并且只释放一次(在析构函数中)。您需要做的是提供由p_int 参数化的Base 构造函数(也可能是a),以便派生类可以提供自己的值:class Base { protected: Base(int * inp_int, int ina) : p_int(inp_int), a(ina) {} ... }; class Child1 : public Base { public: Child1(Child1 const &amp; child) : Base(new int (*child.p_int), child.a + 1) {} ... };。
  • 派生类需要直接访问基类的数据成员有点奇怪,也许您可​​以检查您的设计以获得更好的封装(如果Base包含这些数据成员,它应该负责它们的管理;如果对这些数据的所有操作都是由派生类执行的,那么它可能应该移到那里。每个类的职责都应该明确定义)。
  • 该示例仅显示了我遇到问题的一段代码,而不是实际 Base 类将具有的全部功能。当然,它会使用p_int。

标签: c++ polymorphism type-conversion polymorphic-associations


【解决方案1】:

最简单的解决方案可能是实现一个以Child1&amp; 作为参数的Child2 构造函数。然后你可以简单地调用:

Child2* c2 = new Child2(*c1);

【讨论】:

  • 这应该行不通。复制构造函数需要const Child2&amp;,而不是const Child1&amp;。
  • @Nawaz:它可以接受一个 const Child2&,虽然它不再被称为复制构造函数,而是一个转换构造函数。
  • 我不是建议使用复制构造函数:我建议 @mmm 定义一个新的 Child2 构造函数,它需要一个 Child1&amp; - 即定义 Child2::Child2(const Child1&amp;)
  • @Nawaz:为什么它不起作用? OP 要求的是转换构造函数,而不是复制构造函数,所以这个答案对我来说似乎完全有效。
【解决方案2】:

如果你只有2个子类,那么最简单的方法是创建一个转换构造函数:

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

c2 = new Child2(*c1); 

如果您有多个 Child 类,并且需要从其中的任何一个中创建 Child2,那么您可以执行以下操作:

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); 

【讨论】:

  • 您甚至可以通过将createFrom 静态成员函数设为基类中的模板来避免重复:template &lt;typename Child&gt; static Child * CreateFrom(Base * base) { Child ch = new Child(); ch-&gt;copyFrom(base); return ch; } c2 = Base::CreateFrom&lt;Child2&gt;(c1);
【解决方案3】:
c2 = (Child2*)c1->clone();

这是一个严重的错误,c 样式转换隐藏错误。

如果你使用 C++ 风格的强制转换,那么它不会隐藏错误,你会知道的。在这种情况下,C++ 风格的演员表是:dynamic_cast。使用它来自己发现错误。

从代码中可以清楚地看出c1-clone() 创建了c1 的克隆,其类型为Child1*,clone() 返回一个Base* 类型的指针(在从Child1* 向上转换之后),你'正在尝试向下转换为Child2*。如果您使用正确的演员表,演员表应该会失败:dynamic_cast。

【讨论】:

  • 感谢您的提示,我已经阅读了有关 C++ 风格转换的信息,并且有时使用过它,但这是它第一次真正显示错误。所以也许我必须开始更频繁地使用它:)。
【解决方案4】:

clone() 模式允许您创建仅具有基本引用的子类对象的有效副本/克隆,例如在您的情况下,它允许您执行以下操作:

Base* basePtr = getBaseOrSomeDerivedObject();
Base* copy = basePtr.clone(); // Create a copy that is an object of an actual basePtr's type.

您可能需要一个“复制构造函数”,它允许您从基类复制,例如:

class Base {
public:
    // [...]    
    Base(const Base& other) : a(other.a + 1)
    {
        p_int = new int(*(other.p_int));
    }
    // [...]
};


class Child2 : public Base {
public:
    // [...]
    Child2(const Base& base) : Base(base) {}
    // [...]
};

int main() {
    // [...]
    c2 = new Child2(*c1);
    c2->print();
}

结果:

Child1: 7275360:4 0
Child2: 7340936:4 1

【讨论】:

  • 感谢您提供详细示例,如果我只能将两个答案标记为最佳... :)
猜你喜欢
  • 1970-01-01
  • 2018-08-16
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多