与通用的转换机制相比较,dynamic_cast、const_cast、static_cast、reinterpret_cast提供了更安全、更明确的类型转换。
dynamic_cast
作用
使得指针能够在类层次结构中进行向上转换,而不允许其它转换
语法
dynamic_cast <type-name> (expression)
假设有High和Low两个类,而ph和pl的类型分别为High*和Low*
pl = dynamic_cast<Low *> ph;
则当且仅当Low是High的可访问基类
(直接或间接时),才能将一个Low*指针赋给pl;
否则,该语句只能将空指针赋给pl。
const_cast
作用
该运算符只用于改变const或者volatile属性的类型转换。
语法
const_cast <type-name> (expression)
High bar;
const High *pbar = &bar;
High *pb = const_cast<High *> (pbar);
//有效操作,仅仅将const High *指针转换为High *指针。
const Low *pl = const_cast<const Low *> (pbar);
//非法操作,这句代码是将const High *转换为const Low *
static_cast
作用
当且仅当type-name可被隐式转换为expression所属类型,或者expression可被隐式转换为type-name所属类型时,使用static_cast才是合法的,否则将出错。
语法
static_cast <type-name> (expression)
假如High是Low的基类,而Pond是一个无关的类
High bar;
Low blow;
High *pb = static_cast<High *> (&blow);
//合法的,Low *指针转换为High *;
Low *pl = statuc_cast<Low *>(&bar);
//合法的,High *指针转换为Low *指针。
Pond *pmer = static_cast<Pond *> (&blow);
//非法的,Low *指针无法转换为Pond *指针。
reinterpret_cast
作用
用于危险的类型转换,它不允许删除const。
语法
reinterpret_cast <type-name> (expression)