C++虚函数(8) - RTTI(Run-time type information)
2015-05-26 00:46
197 查看
C++中, 只有当类中包含至少一个虚函数时,RTTI(Run-time type information)才生效。
编译器会将RTTI保存在vtable中。
例如, dynamic_cast会使用RTTI,下面程序会编译失败。因为类B中没有虚函数。
“cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ”
给类B添加一个虚函数后,工作正常。
works
编译器会将RTTI保存在vtable中。
例如, dynamic_cast会使用RTTI,下面程序会编译失败。因为类B中没有虚函数。
#include<iostream> class B { }; class D: public B {}; int main() { B *b = new D; D *d = dynamic_cast<D*>(b); if(d != NULL) std::cout<<"works"; else std::cout<<"cannot cast B* to D*"; return 0; }编译器会报错:
“cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ”
给类B添加一个虚函数后,工作正常。
#include<iostream> class B { virtual void fun() {} }; class D: public B { }; int main() { B *b = new D; D *d = dynamic_cast<D*>(b); if(d != NULL) std::cout<<"works"; else std::cout<<"cannot cast B* to D*"; return 0; }输出:
works
相关文章推荐
- Run-time type information--RTTI
- RTTI (Run-time type information) in C++
- RTTI(Run-Time Type Information,通过运行时类型信息) 运行期类型检查
- c++模拟MFC中运行时类型识别(RTTI)(Run-Time Type Identification)
- RTTI(Run-Time Type Identification)
- RTTI(Run-Time Type Identification)、虚函数和虚基类的实现方式、开销分析及使用指导
- 从头认识java-12.1 为什么需要RTTI(Run-Time Type Identification)?
- Lession 26 RTTI (Run Time Type Identification)
- Advanced Run Time Type Identification in C++ Part II(Property Library An Implementation of RTTI in C++)
- RTTI (Run-Time Type Identification,通过运行时类型识别)
- 行时类型识别(RTTI, Run-Time Type Identification)是Java中非常有用的机制 多态 类加载
- RTTI(Run-Time Type Identification,通过运行时类型识别)
- [书摘]Issues about RTTI (Run Time Type Identification)
- RTTI(Run-time Type Identification)
- The C++ Standard Library: RTTI(Run-Time Type Identification,运行时类型识别)
- RTTI的魅力(运行时类型识别 Run-time type Identification)
- 从头认识java-12.1 为什么需要RTTI(Run-Time Type Identification)?
- ABAP RTTI(Run Time Type Identification)介绍与反射机制
- 第22章:run time type information
- 迷思微软两大框架的RTTI(Run-Time Type Identification)