首页 > 解决方案 > 多态类的typeid,当给定一个派生类的指针时,说它是一个指向基类的指针!为什么?

问题描述

g++ 6.3.1。

gdb次会议说明dynamic_cast<>了正确的做法,并且编译器显示了派生的vtbl. dynamic_cast<>错误的派生类正确返回0,而正确的类返回正确的指针。Yes显示基类(或对其进行修改)typeid().name(),!P2TEBase为什么会这样?

(gdb) whatis pteExpect
type = TEBase *

(gdb) p *pteExpect
$1 = {
  _vptr.TE = 0x43cef8 <vtable for TEDerived1+16>
}

(gdb) p dynamic_cast<TEDerived2*>(pteExpect)
$2 = (TEDerived2*) 0x0

(gdb) p dynamic_cast<TEDerived1*>(pteExpect)
$3 = (TEDerived1*) 0x43cef8 <vtable for TEDerived1+16>

(gdb) l 170
170    Error( "Required %s not found", typeid( pteExpect ).name() );

(gdb) n
Reading in symbols for akstatus.c...done.
E 10.09 18:18:07.438818 main.cpp:170 Expect() - Required P2TEBase not found

标签: c++rttitypeid

解决方案


typeid在指向的指针TEBase上被调用,因此该变量的类型确实是指向基本类型的指针,即使它碰巧指向其他东西。

为了记录派生类的类名,只需使用typeid( *pteExpect ).name(),您将看到9TEDerivedg++ 6.3.1 将产生的错误名称。现在,您不是在询问指针(TE即使对象不是基类,也始终是指向的指针),而是现在您询问的是指向的东西,对于多态类的派生类, 是派生类。


推荐阅读