C++的显式类型转换

C++的显式类型转换共分为四种:
static_cast
任何具有明确定义的类型转换,只要不包含底层const,都可以使用static_cast

int i=10;
double f=static_cast<float>(i);
int *p=&i;
double *q=static_cast<float*>(p);

其他的类型转换类似了,只要不是转换底层const就行,底层const的转换有下面的函数。
const_cast
用于改变运算对象的底层const

const char*cp;
char *q=static_cast<char*>(cp);//错误,不能转换顶层const
static_cast<string>(cp);//正确,字符串字面值转换成string类型。
const_cast<string>(cp);//错误,const_cast只能改变常量属性

reinterpret_cast
reinterpret_cast通常为运算对象的位模式提供较低层次上的重新解释。举个例子:

int *ip;
char *pc=reinterpret_cast<char*>(ip);

我们必须牢记pc所指的真是对象是一个Int而非字符,如果把pc当成普通的字符指针使用就可能在运行时发生错误。例如:
string str(pc);
使用reinterpret_cast是非常危险的,因为pc的底层指向的是int型的地址,编译器却把它当做了char*型的,这样初始化str可能会瞒过编译器从而造成糟糕的结果,所以想使用reinterpret_cast必须对涉及的类型和编译器实现转换的过程都非常了解。
dynamic_cast
分为指针类型dynamic_cast和引用类型的dynamic_cast
dynamic_cast

If( Derived *dp = dynamic_cast<Derived*>(bp))

{

//使用dp指向的Derived对象

}else{  //bp指向一个Base对象

  //使用bp指向的Base对象

}

如果bp指向Derived对象,则上述的类型转换初始化dp并令其指向bp所指的Derived对象。此时,if语句内部使用Derived操作的代码是安全的。否则,类型转换的结果为0,dp为0意味着if语句的条件失败,此时else执行Base操作。

引用类型的dynamic_cast不会产生空引用,会抛出异常。

猜你喜欢

转载自blog.csdn.net/qq_36946274/article/details/80836960