我想执行指向多态类的指针的STL容器的"深层副本" .
我知道Prototype设计模式,通过Virtual Ctor Idiom实现,如C++ FAQ Lite,第20.8项中所述.
它简单明了:
struct ABC // Abstract Base Class
{
virtual ~ABC() {}
virtual ABC * clone() = 0;
};
struct D1 : public ABC
{
virtual D1 * clone() { return new D1( *this ); } // Covariant Return Type
};
Run Code Online (Sandbox Code Playgroud)
然后是深层复制:
for( i = 0; i < oldVector.size(); ++i )
newVector.push_back( oldVector[i]->clone() );
Run Code Online (Sandbox Code Playgroud)
正如Andrei Alexandrescu 所述:
该
clone()实施必须遵循所有派生类相同的模式; 尽管它具有重复的结构,但没有合理的方法来自动定义clone() …
嗨,我有两个类,一个叫做Instruction,一个叫做LDI,它继承自指令类.
class Instruction{
protected:
string name;
int value;
public:
Instruction(string _name, int _value){ //constructor
name = _name;
value = _value;
}
~Instruction(){}
Instruction (const Instruction &rhs){
name = rhs.name;
value = rhs.value;
}
void setName(string _name){
name = _name;
}
void setValue(int _value){
value = _value;
}
string getName(){
return name;
}
int getValue(){
return value;
}
virtual void execute(){}
virtual Instruction* Clone() {
return new Instruction(*this);
}
};
/////////////end of instruction super class //////////////////////////
class LDI : public Instruction{ …Run Code Online (Sandbox Code Playgroud)