哪种情况下会使用C ++中的克隆以及如何使用它? [英] Which situation will use clone in C++ and how to use it?

查看:203
本文介绍了哪种情况下会使用C ++中的克隆以及如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虚拟克隆和克隆有什么区别?
我找到以下例子,它克隆派生到base,它是什么?

What is the difference between virtual clone and clone? I find the following example, it clone derived to base, what is it for?

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, / p>

// now, b might be of type Base, or Derived, or something else derived from Base

Base * c = b->clone();

//现在,c将与b的类型相同,它不知道它的类型。这是克隆方法有用的。

// Now, c will be of the same type as b was, and you were able to copy it without knowing its type. That's what clone methods are good for.

这篇关于哪种情况下会使用C ++中的克隆以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆