如何克隆为C ++中的派生对象 [英] How to clone as derived object in C++

查看:218
本文介绍了如何克隆为C ++中的派生对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中定义了两个类。 Ones是基类,一个是派生类

I define two classes in C++. Ones is the base class, and one is a derived class

    class CBaseClass
    {
    …
    }

    class CDerivedClass : public CBaseClass
    {
    …
    }

要实现一个克隆函数,如下所示:

And want to implement a clone function as follows:

    CBaseClass *Clone(const CBaseClass *pObject)
    {
    }

当CDerivedClass的对象传递给克隆,那么函数也会创建一个CDerivedClass对象并返回。
当CBaseClass的对象被传递给Clone时,该函数也将创建一个CBaseClass对象并返回。

When an object of CDerivedClass is passed to Clone, then the function will also create a CDerivedClass object and return. When an object of CBaseClass is passed to Clone, then the function will also create a CBaseClass object and return.

如何实现这样的功能? p>

How to implement such a feature?

推荐答案

这里是一个简单的解决方案。记住为继承中的每个类提供一个克隆。

Here is a simple solution. Remember to provide a Clone for each class in the inheritance.

class Base
{
public:
    virtual ~Base() {}
    virtual Base *Clone() const
    {
        // code to copy stuff here
        return new Base(*this);
    }
};

class Derived : public Base
{
public:
    virtual Derived *Clone() const
    {
        // code to copy stuff here
        return new Derived(*this);
    }
};

这篇关于如何克隆为C ++中的派生对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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