c++ - 多态类的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
解决方案
typeid
在指向的指针TEBase
上被调用,因此该变量的类型确实是指向基本类型的指针,即使它碰巧指向其他东西。
为了记录派生类的类名,只需使用typeid( *pteExpect ).name()
,您将看到9TEDerived
g++ 6.3.1 将产生的错误名称。现在,您不是在询问指针(TE
即使对象不是基类,也始终是指向的指针),而是现在您询问的是指向的东西,对于多态类的派生类, 是派生类。
推荐阅读
- java - Inheritance.JOINED,插入导致不必要的更新
- rest - 简单 POST 请求的错误请求
- azure-resource-manager - 如何导出包含其关联 ISE 的逻辑应用的 ARM 模板?
- python-3.x - 如何从 Google BigQuery 行迭代器对象返回字符串?
- javascript - 使用 JS 执行器向 xpath 元素输入文本
- android - Activity 调用 onStop() 时转换共享元素中断
- python - 如何在仅显示数据时禁用表单的字段,但在使用新表单输入数据时启用
- css - 灯塔标记的这个神秘 CSS 是什么?
- citations - Mendeley - 我如何找到与特定引用相关联的文件夹?
- javascript - 如何在 Angular2+ 中为 *ngFor 元素设置锚点?