C++中的类型强制转换相对于C来说来的更加严格。
1)C中强制转换显得较为粗暴,可以在任意类型之间进行转换,编译器很难检查其正确性;
2)难于定位,在源码中无法快速定位所有使用强制类型转换的语句。
强制类型转换在实际工程中几乎是不可能避免的,为此C++将强制类型转换分为4中不同的类型
以提供更加安全可靠的转换。
(1) 静态转换: 用于基本类型之间、有继承关系的类对象之间、类指针之间的转换,不能用于基本
类型指针之间的转换。
static_cast<目标类型>(待转换的值)
double d = 3.14;
double *p = &d;
int a = static_cast<int>(d);
int *p1 = static_cast<int*>(p);//error
2)重解释转换:用于指针类型之间、整数和指针类型之间的转换。
reinterpret_cast<目标类型>(待转换的值)
char c;
char *p1 = &c;
int *p2 =reinterpret<int*>(p1);
unsigned long addr=0x123456;
unsigned long *p = reinterpret<unsigned long *>(addr);
(3)去常量转换: 用于去除变量的只读属性(const/volatile),但是强制转化的目标类型必须是
指针或引用。
const_cast<目标类型>(待转换的值)
eg:
const int &j=1;
int &k = const_cast<int &>(j);
const int x=2;
int &y = const_cast<int &>(x);
int z = const_cast<int>(x);//error,const_cast的目标类型必须是引用或指针。
(4)动态转换: 用于有继承关系的类指针之间、有交叉关系的类指针之间的转换。
dynamic_cast<目标类型>(待转换的值)
具有类型检查的功能(子类指针或引用转换为父亲指针或引用)。
需要虚函数的支持。