15.5

15.5 类型转换运算符

C语言中类型转换过于松散, 允许进行无意义的类型转换。
C++采取更严格地限制允许转换的类型, 并添加四个类型转换运算符, 使转换过程更规范:
dynamic_cast
const_cast
static_cast
reinterpret_cast
dynamic_cast运算符通用语法
dynamic_cast < type-name > (expression)
const_cast运算符执行只有一种用途的类型转换, 即改变值为const或volatile, 语法与dynamic_cast相同:
const_cast < type-name > (expression)
如果类型的其他部分被修改, 上述类型转换将出错。也就是说, 除了const或volatile特征, 可以不同外, type-name和expression的类型必须相同。
使用通用转换也可以, 但是_const_cast更安全
例:必须将指向该空间的地址的const都去掉, 否则依然无法修改该空间的值。
static_cast运算符语法和前面相同:
static_cast < type-name > (expression)
仅当type-name可以被隐式转换为expression时或expression可以被隐式转换位type-name时才是合法的。
可以进行基类和派生类的向上向下转换。
可以对枚举和整型进行转换。
其他int/double/float....
reinterpret_cast运算符用于危险的类型转换。语法相同:
reinterpret_cast < type-name > (expression)
例:
struct dat {short a; short b;};
long value = 0xA224B118;
dat * pd = reinterpret_cast< dat * > (&value);
cout << hex << pd->a;
通常这样的转换依赖于底层编程技术, 是不可移植的。
reinterpret_cast并不支持所有的类型转换, 例如:指针类型可以转换位足以存储指针表示的整型, 但不能见指针转换为更小的整型或浮点型。不能将函数指针转换为数据指针。
C++普通类型转换也受到限制。