C ++ dynamic_cast和typeid进行类比较 [英] C++ dynamic_cast vs typeid for class comparison
问题描述
可能的重复:
C ++等效的instanceof
我想知道 dynamic_cast 和 typeid 仅用于类比较(除了 dynamic_cast 允许访问子类的方法和 typeid 对于类比较是有用的)。我发现一个两年的StackOverflow提出了同样的问题:
C ++等同于instanceof 。然而,它是两岁,我不想necro一个老帖子(和我不确定,当 typeid 出来),所以我想再次问同一个问题有一点点区别。
I was wondering what the difference between dynamic_cast and typeid is in regards to just class comparison (aside from dynamic_cast allowing access to the subclass's methods and typeid only being useful for class comparison). I found a two year old StackOverflow asking the same question: C++ equivalent of instanceof. However, it is two years old and I did not want to necro an old post (and I am unsure when typeid came out), so I thought to re-ask the same question with a slight difference.
基本上,我有A类和B类,它们都是抽象类C的子类。类C被作为参数传入方法,确定类C是否真的是A类或B类。 typeid 和 dynamic_cast 都可以正常工作,因此这是最佳做法/性能问题。我猜:
Basically, I have class A and class B, which are both subclasses of abstract class C. Class C is being taken in as a parameter to a method and I want to determine if class C is really class A or class B. Both typeid and dynamic_cast work properly so this is more of a question of best practice/performance. I am guessing :
A* test = dynamic_cast<A*> someClassCVar
if (test != 0) { //it is of class A }
OR
if (typeid(someClassCVar) == typeid(A)) {
//it is of class A
}
EDIT:很抱歉,位的信息。 ActiveMQ CMS文档声明使用 dynamic_cast ,但我认为这是因为它假设用户想要访问特定于子类的方法。对我来说,如果只需要一个类比较,看起来 typeid 会更好的性能:
http://activemq.apache.org/cms/cms-api-overview.html
Sorry, I forgot to include this bit of information. The ActiveMQ CMS documentation states to use dynamic_cast, but I think that is only because it assumes the user will want to access methods specific to the subclass. To me, it seems that typeid would be better performance if only a class comparison is needed: http://activemq.apache.org/cms/cms-api-overview.html
推荐答案
这两种方法之间有一个重要的区别:
There is an important difference between the two methods:
if(A* test = dynamic_cast<A*>(&someClassCVar)) {
// someClassCVar is A or publicly derived from A
}
其中:
if(typeid(someClassCVar) == typeid(A)) {
// someClassCVar is of class A, not a derived class
}
这篇关于C ++ dynamic_cast和typeid进行类比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!