如何检查对象是否是基类类型

Gil*_* PJ 3 c++ inheritance

我有以下继承层次结构

class A{
  virtual bool fun() = 0;
};

class B: public A{
...
}

class C: public B{
...
}

class D: public C{
...
}

class E: public B{
...
}
Run Code Online (Sandbox Code Playgroud)

在我正在执行的主程序中

for(auto pA: ObjVector)
{
   if(pA->fun()){
       ...
   }
}
Run Code Online (Sandbox Code Playgroud)

现在我想知道pA是否包含基类B对象.据我所知2种方式

  1. dynamic_cast所有派生类的对象和测试,如果它全部失败dynamic_casts并且只传递,B我们确定该对象是类型的B

  2. 再添加一个接口方法,该方法将返回类型enumeration 值并标识该B对象.

是否有其他方法来识别B班级?

Adr*_*ski 6

您可以使用typeid运算符.例如

if (typeid(*pA) == typeid(B)) {
    /* ... ptr points to a B ... */
}
Run Code Online (Sandbox Code Playgroud)

这个工作只有pAB正好时

typeid - 文档