在C ++中复制多态对象 [英] Copying a Polymorphic object in C++
问题描述
我有基类基本
从中派生 Derived1
, Derived2
和
Derived3
。
我已经为一个派生类构造了一个实例存储为
Base * a
。我现在需要做一个对象的深层副本,我将存储为 Base * b
。 据我所知,复制类的正常方法是使用复制构造函数并重载 operator =
。但是,由于我不知道 a
是 Derived1
, Derived2
或 Derived3
,我不能想到使用复制构造函数或 operator =
的方法。我可以想到干净地使这项工作的唯一方法是实现像:
class Base
{
public:
virtual Base * Clone()= 0;
};
和实现 Clone
类如:
class Derivedn:public Base
{
public:
Base * Clone()
{
Derived1 * ret = new Derived1;
复制所有的数据成员
}
};
Java倾向于使用 Clone
有没有更多的C ++方式这样做?
这仍然是我们做的东西在C + +多态类,如果您为对象创建一个复制构造函数(可能是隐式或私有),则不需要对成员进行显式复制。
class Base
{
public:
virtual Base * Clone()= 0;
};
class Derivedn:public Base
{
public:
//这是OK,它的调用协变量返回类型。
Derivedn * Clone()
{
return new Derivedn(* this);
}
private:
Derivedn(const Derivedn):... {}
};
I have base-class Base
from which is derived Derived1
, Derived2
and Derived3
.
I have constructed an instance for one of the the derived classes which I store as Base* a
. I now need to make a deep copy of the object which I will store as Base* b
.
As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=
. However since I don't know whether a
is of type Derived1
, Derived2
or Derived3
, I cannot think of a way of using either the copy constructor or operator=
. The only way I can think of to cleanly make this work is to implement something like:
class Base
{
public:
virtual Base* Clone() = 0;
};
and the implement Clone
in in the derived class as in:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Java tends to use Clone
quite a bit is there more of a C++ way of doing this?
This is still how we do stuff in C++ for polymorphic classes, but you don't need to do the explicit copy of members if you create a copy constructor (possibly implicit or private) for your objects.
class Base
{
public:
virtual Base* Clone() = 0;
};
class Derivedn : public Base
{
public:
//This is OK, its called covariant return type.
Derivedn* Clone()
{
return new Derivedn(*this);
}
private:
Derivedn(const Derivedn) : ... {}
};
这篇关于在C ++中复制多态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!