显式转换

dynamic_cast

支持运行时识别指针或引用所指向的对象。
从基类指针获得派生类行为最好的办法是<font color="blue">通过虚函数</font>。
但是在某些情况下,无法使用虚函数,就需要手动显示转换。
如果转换指针失败,则置0;如果转换引用失败,则抛出bad_cast异常。
 1 if(Extend *ptr = dynamic_cast<Extend *ptr>(ptrBase)
 2 {
 3     // 如果prtBase确实指向Extend,则执行这里
 4 }
 5 else
 6 {
 7     // 如果prtBase并非指向Extend,则执行这里
 8     // 注意:ptr对于这里是不可用的,提高安全性
 9 }
10 
11 void fun(const Base &b)
12 {
13     try
14     {
15         const Derived &d = dynamic_cast<Derived &>(b);
16     }
17     catch(bad_cast)
18     {
19         // 处理引用转换失败情况
20     }
21 }
View Code
 

const_cast

将转换掉表达式的const性质。
1 const char *pc_str;
2 char *pc = string_copy(const_cast<char *>(pc_str));
View Code

static_cast

完成那些编译器隐式执行的任何类型的转换,尤其对从大类型转换至小类型时,免去警告提示。
1 double d = 97.0;
2 char ch = static_cast<char>(d);
View Code

reinterpret_cast

为操作数的位模式提供较低层次的重新解释。
1 int *ip;
2 char *pc = reinterpret_cast<char *>(ip);
View Code
原文地址:https://www.cnblogs.com/TaoyzDream/p/3699755.html