复制对象 - 保持多态性
问题描述
以下代码尝试复制对象并保留原始类型.不幸的是,它不起作用(每个复制的对象都将成为 Super
而不是与其原始对象属于同一类).
The following code tries to copy an object and keep the original type.
Unfortunately it does not work (every copied object will become a Super
instead of being of the same class as its original).
请注意 copySuper(const Super& givenSuper)
不应该知道 Super
的子类.
Please note that copySuper(const Super& givenSuper)
should not know anything about the subclasses of Super
.
可以做这样的副本吗?还是我必须更改 copySuper
的定义?
Is it possible to do such a copy? Or do I have to change the definition of copySuper
?
推荐答案
试试这个:
请注意,我们已经实现了一个 clone() 函数,Special(和 Super 的任何其他派生词)覆盖该函数以创建正确的副本.
Note that we have implemented a clone() function that Special (and any other derivative of Super) overrides to create the correct copy.
例如:
正如其他评论员指出的那样,*this
,而不是 this
.这会教我快速打字.
As other commentator pointed out, *this
, not this
. That'll teach me to type quickly.
另一个更正.
我真的不应该在工作中这么快发帖.为协变返回类型修改了 Special::clone() 的返回类型.
I really should not post so quickly when in the middle of work. Modified return-type of Special::clone() for covariant return-types.
这篇关于复制对象 - 保持多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!