我有Base
派生的基类Derived1
,Derived2
和Derived3
.
我为其中一个派生类构建了一个实例,我将其存储为Base* a
.我现在需要制作一个我将存储的对象的深层副本Base* b
.
据我所知,复制类的正常方法是使用复制构造函数并重载operator=
.但是,因为我不知道是否a
是类型Derived1
,Derived2
或者Derived3
,我想不出使用复制构造函数的方法operator=
.我能想到的唯一方法是干净利落地完成这项工作:
class Base
{
public:
virtual Base* Clone() = 0;
};
Run Code Online (Sandbox Code Playgroud)
和Clone
派生类中的实现如下:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Run Code Online (Sandbox Code Playgroud)
Java倾向于使用Clone
相当多的C++方式更多吗?
Mic*_*son 35
这仍然是我们在C++中为多态类做的事情,但是如果为对象创建了一个复制构造函数(可能是隐式或私有),则不需要执行成员的显式复制.
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) : ... {}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13751 次 |
最近记录: |