虚拟克隆和克隆有什么区别? 我找到下面的例子,它克隆派生到基础,它是做什么用的?
class Base{
public:
virtual Base* clone() {return new Base(*this);}
int value;
virtual void printme()
{
printf("love mandy %d\n", value);
}
};
class Derived : public Base
{
public:
Base* clone() {return new Derived(*this);}
virtual void printme()
{
printf("derived love mandy %d\n", value);
}
};
Derived der;
der.value = 3;
Base* bas = der.clone();
bas->printme();
最佳答案
考虑一下:
Base * b = get_a_base_object_somehow();
//现在,b 可能是 Base 或 Derived 类型,或从 Base 派生的其他类型
Base * c = b->clone();
//现在,c 将与 b 的类型相同,并且您可以在不知道其类型的情况下复制它。这就是克隆方法的用武之地。
关于c++ - C++中哪些情况会用到clone,如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7708110/