在c ++中创建一个未知的具体类型的副本 [英] Make a copy of an unknown concrete type in c++

查看:109
本文介绍了在c ++中创建一个未知的具体类型的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下类层次结构:

  class Base {
...
} ;

class Derived1:public Base {
...
};

class Derived2:public Base {
...
};

给定 Base * 或者一个 Derived1 Derived2 对象如何能够创建一个实际对象的副本,因为它的具体类型是未知的。我想到定义复制构造函数,但我不认为这是可能的,而不知道实际类型涉及。我可以想到的唯一解决方案是在层次结构中的每个类型上定义一个 clone()方法。

解决方案

不幸的是,一个虚拟的克隆/复制模式是你唯一的选择。

这里有一些变化,但基本上它们都是为每个可以返回新副本的类型编写函数。


Suppose we have the following class hierarchy:

class Base {
    ...
};

class Derived1 : public Base {
    ...
};

class Derived2 : public Base {
    ...
};

Given a Base* which could point to either a Derived1 or Derived2 object how can I make a copy of the actual object given that it's concrete type is unknown. I thought of defining copy constructors but I don't think this is possible without knowing the actual types involved. The only solution I can think of is defining a clone() method on each type in the hierarchy. Can anybody think of something more elegant?

解决方案

Unfortunately a virtual clone/copy pattern is your only real choice.

There are variations of this, but essentially they all come down to writing functions for each type that can return a new copy.

这篇关于在c ++中创建一个未知的具体类型的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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