1、 静态转换(static_cast)
static_cast 用于明确定义达到转换,包括编译器允许我们所做的不用 强制转换的安全变换和不太安全但清楚定义的变换。
例子:
int i=47;
double d;
d=static_cast<double> (i);
2、 常量转换(const_cast)
如果从const转换为非const 或从volatile转换为非volatile,就可以直 接使用const_cast,也是唯一允许的转换做法。
例子:
const int a=7;
int *p=const_cast<int *>(&a);
3、 重解释转换(reinterpret_cast)
这是最不安全的一种转化机制,最有可能出问题,reinterpret_cast把对 象假想为模式,是一个完全不同类型的对象,在使用reinterpret_cast做 任何事之前,实际上总是需要reinterpret^ast转换回原来的类型•一 C++中的reinterpretjast主要是将■据从一种类型的转换为另一种类型。 所谓“通常为操作数的位模式提供较低层的重新解释”也就是说将数据以 二进制存在形式的重新解释
主要是将数据从一种数据类型转换成另一种数据类型。 例子:
int i;
char *p ="this is c++";
i=reinterpret_cast<int>(p);
此转换不安全,重解释转换不考虑指针的便宜,只是对二进制形式的重解释。
4、 动态转换(dynamic_cast)
针对继承体系中,dynamic_cast要用于类型安全的向下转化.
//父类 Base
//子类 D
D d;
Base b;
Base *pb;
D *pd=dynamic_cast<D*>(pb);
if(pd ==NULL )
//非法转换