C语言的转换是在变量前加类型名进行转换的,比如
double pi = 3.14;
int a = (int) pi;
对于指针也是如此
double* dptr = π
int* iptr = (int*)dptr;
虽然c++兼容了C语言的转型方式,但是也做了很多限制,比如向上类型转换,在c++中建议使用c++的转型方式
(1). static_cast<type>(expression)
这是普通的类型转换,比如double转int,普通的指针转换,但是无法对const进行转换,他有和C语言类型转换差不多的限制
比如不能把一个类转为另一个类。但是可以支持派生类转为基类。不支持基类转为派生类
(2).const_cast<type>(expression)
消除常量,转换为普通可以修改的变量
(3)dynamic_cast<type>(expression)
用于继承体系的转换,是对指针或者引用的转换,普通常量不行;
并且这种类型转换,正常情况下只能向上做类型转换,不能向下转,只有在虚继承的情况下才有意义,比如实现多态
#include <iostream>
using namespace std;
class Base{};
class Derive: public Base{};
int main(int argc, char** argv) {
Base b;
Derive d;
//理论上来讲,能够向上类型转换
b = d;//正常的转换->隐式类型转化
d = b; //无法从父类转为派生类
return 0;
}
正确的用法
#include <iostream>
using namespace std;
class Base{
public:
virtual ~Base(){}
};
class Derive: public Base{};
int main(int argc, char** argv) {
Base b;
Derive d;
Derive pd = dynamic_cast<Derive&>(d);
return 0;
}
(4)reinterpret_cast<type>(expression)
这是一个和操作平台息息相关的类型转换,主要用于函数指针的类型转换