繁体   English   中英

当我有一个指向其基类的指针时,该对象是否克隆?

[英]Clone an object when I have a pointer to its base class?

我有多个类(比如说B和C),它们继承了一些抽象基类(比如说A)。 我有一个指向类A的指针(p1),它实际上是指向类B或类C的对象(o1)。然后我有另一个指向类A的指针(p2),我想使其指向另一个对象( o2)与o1相同。 问题在于那一刻我不知道o1是什么类型。

A* newObject() //returns pointer to A which actually points to an object of class B or class C
{
     ....
}
A * p1 = newObject();
A * p2 = //I want it to point to a new object that is the same as the object p1 is pointing to. How can I do that?

我需要这样做,因为我正在实现一种遗传算法,并且我有多种类型的控制类别,然后我想对其进行突变。 当复制某些东西时,我希望孩子与父母相同,然后再对孩子进行突变。 这意味着p2不能等于p1,因为这也会使父级的控制器发生变化。

将虚拟方法Clone()添加到类中。

class A {
public:
    virtual ~A() = default;

    auto Clone() const { return std::unique_ptr<A>{DoClone()}; }
    // ...
private:
    virtual A* DoClone() const { return new A(*this); }
};

class B : public A {
public:
    auto Clone() const { return std::unique_ptr<B>{DoClone()}; }
    // ...
private:
    // Use covariant return type :)
    B* DoClone() const override { return new B(*this); }
    // ...
};

class C : public A {
public:
    auto Clone() const { return std::unique_ptr<C>{DoClone()}; }
    // ...
private:
    // Use covariant return type :)
    C* DoClone() const override { return new C(*this); }
    // ...
};

接着

auto p2 = p1->Clone();

暂无
暂无

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

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