1、typeid
通过运行时类型识别(RTTI),程序能够使用基类的指针或引用来检索这些指针或引用所指对象的实际类型。
c++可以通过下面两个操作提供RTTI
1、typeid操作符,返回指针或引用所指对象的实际类型。
2、dynamic_cast操作符,将基类类型的指针或引用安全的转换为派生类型的指针或引用。
用法:
Base *bp;
Derived *dp;
if(typeid(*bp)==typeid(*dp)){```}1
if(typeid(*bp)==typeid(Derived)){```}2
1、比较bp所指对象与dp所指对象的实际类型,如果它们指向同一个类型,则测试成功。类似的,如果bp当前指向derived对象,则2测试成功
显式转换
强制类型转换符:static_cast、dynamic_cast、const_cast,reinterpret_cast。
reinterpret_cast
之前是采用圆括号将类型括起来实现
int *p;
char *pc=reinterpret_cast<char*>(ip);
效果等同于:
int *ip;
char*pc=reinterpret_cast<char*>(ip);
const_cast
转换掉const性质
const char *pc_str;
char *pc=const_cast<char*>(pc_str);
例如:
const double value=0.0f;
double* ptr=NULL;
怎么让ptr指向value?
强制类型转换,去掉const属性
ptr=const_cast<double*>(&value)
static_cast
编译器隐式执行的任何类型转换都可以有static_cast显示完成:
都变了double d= 97.0;int i=static_cast<int>(d);