复制抽象基类的对象
如果我有一个指向派生自抽象基类的对象的指针(因此我无法创建该类的新对象),并且我希望制作该对象的深层副本,是否有比这更简洁的方法来实现这一点让抽象基类创建一个新的纯虚复制函数,每个继承类都必须实现该函数?
If I have a pointer to an object that derives from an abstract base class (so I cannot create an new object of that class), and I wish to make a deep copy of said object, is there a more concise way of accomplishing that than to have the abstract base class create a new pure virtual copy
function that every inheriting class has to implement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,但是
copy
方法不一定很痛苦:(假设您已经有一个复制构造函数,如果您需要深层复制,您就会有)。
No, but the
copy
method does not have to be painful:(assuming you already have a copy constructor, which, if you need a deep copy, you'll have).
建议的“复制”(通常称为“克隆”)是正常方法。另一种选择是使用 rtti 的工厂和调度来找到正确的处理程序,然后调用派生类型的复制构造函数。
虽然上述方法有效,但它使用 rtti 的事实足以说服大多数人采用正常方法。但是,如果有原因阻止对基类进行更改,那么它可能会很有用。
这么有效率吗?增加一种新类型的边际成本确实是一笔小钱。问题是很容易忘记在每个新类中添加该行。或者您可以将其视为一个优点,即所有克隆代码都位于单个文件中,并且我们不必更改支持的层次结构来处理它。
The suggested 'copy', more usually called 'clone' is the normal approach. An alternative would be a factory and dispatch using rtti to find the right handler to then call the copy constructor on the derived type.
Whilst the above works, the sheer fact it uses rtti would be enough to persuade most to go the normal approach. However, it there was a reason preventing changes to the base class, it might be useful.
It this efficient? The marginal cost of adding a new type is truly a one-liner. The catch is that it will be easy to forget to add that line with each new class. Or you can see it as an upside that all the clone code lives in a single file and we don't have to change the supported hierarchy to handle it.
不久前,comp.lang.c++ 中有人询问如何自动创建clone() 函数。其他人提供了一个想法,我在此基础上进行了扩展。它们都不是经过测试的代码,我从未真正尝试过......但我认为它有效: http: //groups.google.com/group/comp.lang.c++/browse_thread/thread/c01181365d327b2f/9c99f46a8a64242e?hl=en&ie=UTF-8&oe=utf-8&q=comp.lang.c%2B% 2B+诺亚+罗伯茨+克隆&pli=1
A while back someone in comp.lang.c++ asked how to automatically create a clone() function. Someone else provided an idea upon which I expanded. None of it is tested code and I've never actually tried it...but I think it works: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/c01181365d327b2f/9c99f46a8a64242e?hl=en&ie=UTF-8&oe=utf-8&q=comp.lang.c%2B%2B+noah+roberts+clone&pli=1