我是幸运儿,幸运儿是我。

C++ 既支持 C 风格的类型转换,又有自己风格的类型转换。C 风格的转换格式很简单,但是有不少缺点:
- 转换太过随意,可以在任意类型之间转换。你可以把一个指向 const 对象的指针转换成指向非 const 对象的指针,把一个指向基类对象的指针转换成一个派生类对象的指针,这些转换之间的差距是非常巨大的,但是传统的C语言风格的类型转换没有区分这些。
- C 风格的转换没有统一的关键字和标示符。对于大型系统,做代码排查时容易遗漏和忽略。
C++ 风格完美的解决了上面两个问题。
- 对类型转换做了细分,提供了四种不同类型转换,以支持不同需求的转换;
- 类型转换有了统一的标示符,利于代码排查和检视。
下面分别来介绍这四种转换:static_cast、dynamic_cast、const_cast、reinterpert_cast,它们都是类模板。
格式均为:xx_cast<type-id>(expression) ,其中type-id-要转换成什么类型,expression-被转换类型的目标变量
一、static_cast(静态转换)
(1)使用场景
- 在基本数据类型之间转换,如把 int 转换为 char,这种带来安全性问题由程序员来保证;
- 在有类型指针与 void * 之间转换;
- 用于类层次结构中基类和派生类之间指针或引用的转换。
- 上行转换(派生类---->基类)是安全的;
- 下行转换(基类---->派生类)由于没有动态类型检查,所以是不安全的。
- 【记住:父类转换成子类是类型不安全的,我的理解是父类不知道这个子类到底是不是我的儿子】
 
(2)使用特点
- 主要执行非多态的转换操作,用于代替C中通常的转换操作。
- 隐式转换都建议使用 static_cast 进行标明和替换。
- 不能使用 static_cast 在有类型指针内转换。
(3)示例程序如下所示:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 
 | #include <iostream>using namespace std;
 class CBase
 {};
 class CDerived : public CBase
 {};
 int main()
 {
 
 float fval = 10.12;
 int ival = static_cast<int>(fval);
 cout << ival << endl;
 
 
 int *intp = &ival;
 void *voidp = static_cast<void *>(intp);
 
 long *longp = static_cast<long *>(voidp);
 cout << *longp << endl;
 
 
 
 CDerived *tCDerived1 = nullptr;
 CBase *tCBase1 = static_cast<CBase*>(tCDerived1);
 
 CBase *tCBase2 = nullptr;
 CDerived *tCDerived2 = static_cast<CDerived*>(tCBase2);
 
 
 float *floatp = &fval;
 
 cout << *floatp << endl;
 }
 
 
 
 
 
 
 
 
 
 | 
失败的情况
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | #include <iostream>
 class Base {};
 class Derived : public Base {};
 class Unrelated {};
 
 int main() {
 Base* base = new Base();
 
 Derived* derived = static_cast<Derived*>(base);
 
 
 
 
 delete base;
 return 0;
 }
 
 
 | 
二、dynamic_cast(动态转换)
记住那个
(1)使用场景
- 用于将一个父类的指针/引用转化为子类的指针/引用(下行转换)。
(2)使用特点
- 基类必须要有虚函数,因为 dynamic_cast 是运行时类型检查,需要运行时类型信息,而这个信息是存储在类的虚函数表中。
- 对于下行转换,dynamic_cast 是安全的(当类型不一致时,转换过来的是空指针),而 static_cast 是不安全的。
- 对指针进行 dynamic_cast,失败返回 NULL,成功返回正常 cast 后的对象指针;对引用进行 dynamic_cast,失败抛出一个异常,成功返回正常 cast 后的对象引用。
- 对于指针类型,如果转换失败,返回 nullptr。
- 对于引用类型,如果转换失败,会抛出 std::bad_cast异常。
(3)示例程序如下所示:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 
 | #include <iostream>#include <typeinfo>
 
 class Base {
 public:
 virtual ~Base() {}
 };
 
 class Derived : public Base {};
 class AnotherDerived : public Base {};
 
 int main() {
 Base* base = new Base();
 Derived* derived = dynamic_cast<Derived*>(base);
 
 if (derived == nullptr) {
 std::cout << "dynamic_cast 失败,base 不是 Derived 类型。" << std::endl;
 }
 
 try {
 Base& baseRef = *base;
 Derived& derivedRef = dynamic_cast<Derived&>(baseRef);
 } catch (const std::bad_cast& e) {
 std::cout << "dynamic_cast 失败,抛出异常: " << e.what() << std::endl;
 }
 
 delete base;
 return 0;
 }
 
 
 | 
dynamic_cast的工作机制如下:
- 首先,dynamic_cast检查p_CBase的动态类型。动态类型是指针或引用实际指向的对象的类型,它可能与指针或引用的静态类型(在源代码中声明的类型)不同。在C++中,如果一个类有虚函数,编译器就会为这个类的每个对象添加一个指向虚函数表的指针,这个虚函数表中存储了对象的动态类型信息。
- 接着,dynamic_cast比较p_CBase的动态类型和目标类型CBase。如果p_CBase的动态类型是CBase,或者是CBase的派生类,那么dynamic_cast就会成功,返回一个指向CBase的指针。否则,dynamic_cast就会失败,返回空指针。
- dynamic_cast的这种行为可以保证类型转换的安全性。如果我们试图转换一个并非CBase或CBase的派生类的对象为CBase,dynamic_cast就会返回空指针,以此表示转换失败。这样,我们就不会错误地将一个并非CBase对象的指针当作CBase对象的指针来使用,从而避免了可能的未定义行为。
有个疑问:怎么比较判断CDerived是p_CBase的派生类?
虚函数表中的RTTI包括以下信息:
- 类型的名称
- 类型的哈希值(用于比较两个类型是否相同)
- 类型的基类和派生类的信息
- 类型的大小
当我们使用dynamic_cast进行下行转换时,dynamic_cast会查看指针指向的对象的虚函数表中的RTTI,判断目标类型是否与对象的动态类型相符,或者是否为其派生类。
| 1
 | Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
 | 
是检测basePtr的RTTI
失败的例子
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 
 | #include <iostream>#include <typeinfo>
 
 class Base {
 public:
 virtual ~Base() {}
 };
 
 class Derived : public Base {};
 class AnotherDerived : public Base {};
 
 int main() {
 Base* base = new Base();
 Derived* derived = dynamic_cast<Derived*>(base);
 
 if (derived == nullptr) {
 std::cout << "dynamic_cast 失败,base 不是 Derived 类型。" << std::endl;
 }
 
 try {
 Base& baseRef = *base;
 Derived& derivedRef = dynamic_cast<Derived&>(baseRef);
 } catch (const std::bad_cast& e) {
 std::cout << "dynamic_cast 失败,抛出异常: " << e.what() << std::endl;
 }
 
 delete base;
 return 0;
 }
 
 
 | 
注意点:
如果是上行转换,也就是子类转换成父类,不用加virtual是不会爆红的
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | #include <iostream>#include <typeinfo>
 using namespace std;
 class CBase
 {
 
 };
 class CDerived : public CBase
 {};
 int main()
 {
 CDerived *tCDerived1 = new CDerived();
 CBase *tCBase1 = dynamic_cast<CBase*>(tCDerived1);
 }
 
 | 
但是,如果是下行转换,那么不加virtual是会爆红的,因为要进行类型检查,类型检查根据虚函数表进行的。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | #include <iostream>#include <typeinfo>
 using namespace std;
 class CBase{
 
 };
 class CDerived : public CBase
 {};
 int main(){
 CBase *tCDerived1 = new CBase();
 CBase *tCBase1 = dynamic_cast<CDerived*>(tCDerived1);
 }
 
 | 
三、const_cast(常量转换)
(1)使用场景
- 常量指针(或引用)与非常量指针(或引用)之间的转换。
(2)使用特点
- cosnt_cast 是四种类型转换符中唯一可以对常量进行操作的转换符。
- 去除常量性是一个危险的动作,尽量避免使用。
(3)示例程序如下所示:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | #include <iostream>
 using namespace std;
 
 int main()
 {
 int value = 100;
 const int *cpi = &value;
 
 
 
 int *pi = const_cast<int *>(cpi);
 *pi = 200;
 
 
 const int *cpi2 = const_cast<const int *>(pi);
 
 const int value1 = 500;
 const int &c_value1 = value1;
 
 
 int &r_value1 = const_cast<int &>(c_value1);
 
 
 const int &c_value2 = const_cast<const int &>(r_value1);
 }
 
 | 
四、reinterpret_cast(不相关类型的转换)
reinterpret 的英文含义有重新转换的含义,就相当于 C 语言中不相关类型的转换,强转。
(1)使用场景
- 用在任意指针(或引用)类型之间的转换。
- 能够将整型转换为指针,也可以把指针转换为整型或数组。
(2)使用特点
- reinterpret_cast 是从底层对数据进行重新解释,依赖具体的平台,可移植性差。
- 不到万不得已,不用使用这个转换符,高危操作。
(3)示例程序如下所示:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | #include <iostream>
 using namespace std;
 
 int main()
 {
 int value = 100;
 
 double *pd = reinterpret_cast<double *>(&value);
 cout << "*pd = " << *pd << endl;
 
 
 int *pv = &value;
 int pvaddr = reinterpret_cast<int>(pv);
 cout << "pvaddr = " << hex << pvaddr << endl;
 cout << "pv = " << pv << endl;
 }
 
 
 
 
 
 
 
 
 
 | 
学习自:C++中的四种强制类型转换符详解