用于类比较的 C++ dynamic_cast 与 typeid

C++ dynamic_cast vs typeid for class comparison(用于类比较的 C++ dynamic_cast 与 typeid)

本文介绍了用于类比较的 C++ dynamic_cast 与 typeid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
C++ 等效的 instanceof

我想知道 dynamic_casttypeid 之间的区别仅在于类比较(除了 dynamic_cast 允许访问子类的方法和 typeid 仅用于类比较).我发现一个两年前的 StackOverflow 也在问同样的问题:C++ 等效的 instanceof.然而,它已经两年了,我不想死掉一个旧帖子(我不确定 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 类.typeiddynamic_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 }

if (typeid(someClassCVar) == typeid(A)) {
   //it is of class A
}

抱歉,我忘记包含这些信息了.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:用于类比较的 C++ dynamic_cast 与 typeid

基础教程推荐