在c++中什么情况下使用克隆,以及如何使用它

Which situation will use clone in C++ and how to use it?

本文关键字:何使用 c++ 什么 什么情况 情况下      更新时间:2023-10-16

虚拟克隆和克隆有什么区别?我找到下面的例子,它克隆派生到基,它是干什么用的?

class Base{
public:
    virtual Base* clone() {return new Base(*this);}
    int value;
    virtual void printme()
    {
        printf("love mandy %dn", value);
    }
};
class Derived : public Base
{
public:
    Base* clone() {return new Derived(*this);}
    virtual void printme()
    {
        printf("derived love mandy %dn", value);
    }
};
Derived der;
    der.value = 3;
    Base* bas = der.clone();
    bas->printme();

考虑一下:

Base * b = get_a_base_object_somehow();

//现在,b的类型可以是Base,派生的,或者是从Base派生的

Base * c = b->clone();

//现在,c和b的类型是一样的,你可以在不知道它的类型的情况下复制它。

考虑一下:

Base* p1 = &der;
Base* p2 = p1->clone()
p2->printme();

如果clone()不是虚拟的,结果将是"love mandy 3"。如果是虚拟的,结果将是"derived love mandy 3"。