在C语言中转换的意义是:编译器你把XXX看做这个类型
这样会带来不安全,所以C++中改良转换,并且提供四个关键字:
static_cast
基本上的功能是和c的转换一致(编译器你把XXX看做这个类型),但是功能有所弱化,例如:不能把指针转化成int 型。
1。The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class.(类的指针转换)
注:在有类的继承关系时,static_cast根据 移指针的方式来确定子类中包含的父类的指针(Com中的应用原理在此),因为编译器有足够的信息知道子类中父类的指针在哪儿。
2。In general you use static_cast when you want to convert numeric data types such as enums to ints or ints to floats, and you are certain of the data types involved in the conversion.(基本数据类型之间的转换)
const_cast
把const转换成非const,但是只能是转换到相应类型的非const类型
把volatile转换成非volatile,可以不必转换成相应类型的volatile
dynamic_cast
利用RTII功能在运行时检查指针类型,也就是说在类的指针向下转换时它时安全的,它能识别类型。转换成功返回相应指针,否则返回0
reinterpret_cast
就是重新解释类型的意思
The reinterpret_cast operator allows any pointer to be converted into any other pointer type. It also allows any integral type to be converted into any pointer type and vice versa.
从指针 到 整形 ok
从整形 到 指针 ok
从指针 到 指针 ok