RTTI的魅力(运行时类型识别 Run-time type Identification)
来源:互联网 发布:椭圆拟合编程 编辑:程序博客网 时间:2024/05/16 08:58
一句话总结:实际运行时检查指针或者引用指向的实际派生类型。
两个重要的哼哈二将:typeid、dynamic_cast
#ifndef CRTTI_hpp
#define CRTTI_hpp
#include <iostream>
class CPerson
{
public:
void getup(){std::cout<<"getup..."<<std::endl;}
void sleep(){std::cout<<"sleep..."<<std::endl;}
virtual ~CPerson(){}//这个很重要,没有这个,RTTI就不要玩了
public:
int age;
int tall;
};
class CFarmer: publicCPerson
{
public:
void farming(){std::cout<<"farming..."<<std::endl;};
};
class CWorker: publicCPerson
{
public:
void building(){std::cout<<"building..."<<std::endl;};
};
#endif /* CRTTI_hpp */
#include <iostream>
#include "CRTTI.hpp"
using namespacestd;
void doAction(CPerson* obj)
{
cout<<typeid(*obj).name()<<endl;
obj->getup();
if (typeid(*obj) ==typeid(CFarmer)) {
CFarmer* farmer =dynamic_cast<CFarmer*>(obj);
farmer->farming();
}
else{
cout<<"who are you"<<endl;
}
obj->sleep();
}
int main(int argc,constchar * argv[]) {
// insert code here...
CFarmer farmer;
doAction(&farmer);
CWorker *worker =newCWorker();
doAction(worker);
delete worker;
return0;
}
运行结果:
7CFarmer
getup...
farming...
sleep...
7CWorker
getup...
who are you
sleep...
Program ended with exit code: 0
dynamic_cast注意事项:
1、只能应用于指针和引用之间的转换
2、要转换的类型中必须包含虚函数
3、转换成功返回子类的地址,失败返回null
typeid注意事项:
1、type_id返回一个type_info对象的引用
2、基类必须带有虚函数,否则通过基类获得的数据类型依旧是基类
- RTTI的魅力(运行时类型识别 Run-time type Identification)
- C++ Run-Time Type Identification(RTTI)运行时类型识别
- Java RTTI(Run-Time Type Identification) 运行时类型识别
- c++模拟MFC中运行时类型识别(RTTI)(Run-Time Type Identification)
- RTTI(Run-Time Type Identification,通过运行时类型识别)
- RTTI (Run-Time Type Identification,通过运行时类型识别)
- The C++ Standard Library: RTTI(Run-Time Type Identification,运行时类型识别)
- RTTI(Run-time Type Identification)
- C++ RTTI(Run-Time Type Indentifiation,运行时刻类型识别)
- RTTI(Run-Time Type Identification)
- RTTI(runtime type information Identification) 运行时类型识别
- RTTI(RunTime Type Identification,运行时类型识别)
- RTTI运行阶段类型识别(Runtime Type Identification)
- 行时类型识别(RTTI, Run-Time Type Identification)是Java中非常有用的机制 多态 类加载
- RTTI(Run-Time Type Information,通过运行时类型信息) 运行期类型检查
- Lession 26 RTTI (Run Time Type Identification)
- MFC中的RTTI(Runtime Type Identification, 运行时类型识别)详解(参考《深入浅出MFC》)
- 7.3 执行期类型识别(Runtime Type Identification,RTTI)
- 菜鸟先飞之JAVA_内存分配
- 找出无序数组中的最小的k个数(利用大根堆)
- 变量的高级主题
- LintCode python 小白7-超级丑数
- 逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表
- RTTI的魅力(运行时类型识别 Run-time type Identification)
- RESTAPI设计规则
- java 第四章
- 从键盘输入某个十进制小数或整数,转换成对应的二进制小数并输出。 (查询十进制小数转换成二进制小数的算法,使用循环来实现。 最多保留小数位后7位数字即可)算法
- hdu 2021 发工资咯:)贪心
- 什么是VBI
- Futexes Are Tricky
- 170715 如何更改CSDN上传图片大小
- POJ 1504 Adding Reversed Numbers(字符串巧解)