指向对象的指针向量,需要向量的深拷贝,但对象是继承对象的基础
我想要一个带有指向对象的指针的向量的深层副本,但该对象可以是 C 或 B。我知道令人困惑(我解释它的方式),让我举例说明。
class A {
A(const A& copyme) { }
void UnableToInstantiateMeBecauseOf() =0;
};
class B {
B(const B& copyme) : A(copyme) {}
};
class C {
C(const C& copyme) : A(copyme) {}
};
std::vector<A*>* CreateDeepCopy(std::vector<A*>& list)
{
std::vector<A*>* outList = new std::vector<A*>();
for (std::vector<A*>::iterator it = list.begin(); it != list.end(); ++it)
{
A* current = *it;
// I want an copy of A, but it really is either an B or an C
A* copy = magic with current;
outList->push_back(copy);
}
return outList;
}
如何创建一个您不知道其继承类型的对象的副本?
I want to have a deep copy of an vector with pointers to objects, but the object can either be C or B. I know confusing (the way I explain it), let me illustrate.
class A {
A(const A& copyme) { }
void UnableToInstantiateMeBecauseOf() =0;
};
class B {
B(const B& copyme) : A(copyme) {}
};
class C {
C(const C& copyme) : A(copyme) {}
};
std::vector<A*>* CreateDeepCopy(std::vector<A*>& list)
{
std::vector<A*>* outList = new std::vector<A*>();
for (std::vector<A*>::iterator it = list.begin(); it != list.end(); ++it)
{
A* current = *it;
// I want an copy of A, but it really is either an B or an C
A* copy = magic with current;
outList->push_back(copy);
}
return outList;
}
How to create an copy of an object of which you don't what inherited type it is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用克隆:
复制对象 - 保持多态性
编辑:
我在你的问题中注意到你的基类是抽象的。没关系,这个模型仍然有效,我已经修改了。
Use cloning:
Copy object - keep polymorphism
EDIT:
I noticed in your question your base-class is abstract. That's fine, this model still works, I have amended.
将虚拟 Clone() 方法添加到您的类中。
重写派生类中的克隆。实现与 A 类相同。
Add a virtual Clone() method to your classes.
Override Clone in derived classes. The implementation is the same as with class A.
您可以在类
A
中实现纯虚拟克隆函数。You could implement a pure virtual clone function in class
A
.正如其他人所说,您需要某种类型的克隆机制。您可能想查看 Kevlin Henney 在他的优秀论文中的
cloning_ptr
单独克隆。As others have said you need some type of cloning mechanism. You might want to check out the
cloning_ptr
by Kevlin Henney in his excellent paper Clone Alone.