问题描述
这个问题似乎可能有些常见,但是我在找到StackOverflow或interwebs时没有发现任何东西。
This question seems like it might be somewhat common, but I didn't find anything when scowering StackOverflow or the interwebs.
我遇到了一个C ++中的方法类,它接受一个(例如) Parent
对象的列表。对于这个例子,假设有两个派生自 Parent
: Child1
和 Child2
I came across a method in a C++ class that takes a list of (for example) Parent
objects. For this example, assume that there are two classes that derive from Parent
: Child1
and Child2
.
对于列表中的每个对象,该方法检查对象是否为 Child2
(通过每个类实现的 IsOfType()
方法),如果是这样,它调用只由 Child2
class。
For each object in the list, the method checks if the object is of type Child2
(via a IsOfType()
method that each class implements), and if so, it calls a method that is only provided by the Child2
class.
这是一个问题,因为列表处理方法不能处理每个对象相同?我已经在其他地方看到这样做,所以它似乎在某种程度上是一个常见的做法。
Is this an issue in that the list-processing method cannot treat each object the same? I've seen this done in other places as well, so it seems it might be a common practice to some degree.
一个选项可能是声明父
类中的$ c> Child2 方法,以便所有 Parent
对象实现它。但是,在这种情况下,只有 Child2
类才会实现在覆盖方法时的任何行为。
One option might be to declare the Child2
method in the Parent
class so that all Parent
objects implement it. However, in this case, only the Child2
class would actually implement any behavior when overriding the method.
您的想法?提前感谢!
推荐答案
如果您的IsOfType()测试通过,您可以将Child2对象并访问其特定的成员函数。
If your IsOfType() test passes, you can cast the (pointer to the) parent object to a Child2 object and access its specific member functions.
编辑:
这取决于你的设计以及你确保IsOfType (即在一周内添加新的子类时也可以工作)。使用内置可能更安全。
实现每个可能的方法任何孩子将永远在父中将是困难的,所以upcasting确定当方法真正语义特定于Child2类。
This depends on your design and on how strict you ensure the IsOfType() implementation will give correct answers (i.e. it also works when you add new subclasses in a week). It might be safer to make use of the builtin Typeid instead.Implementing every possible method any child would ever have in the parent would be difficult, so upcasting is ok when the method is really semantically specific to the Child2 class.
这篇关于在处理父类对象的列表时调用“子类”方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!