文章

类型转换

类型转换

[TOC]

dynamic_cast

动态转换(dynamic_cast)通常用于处理继承关系中的类型转换,用于运行时进行多态类型指针的转换。主要用于将父类指针或引用类型转换为子类指针或引用。在转换过程中会进行类型检查,若两类型非父子关系,则会返回NULL或报错。1

1
2
3
4
5
6
7
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr != nullptr) {
    // 转换成功,可以安全使用
} else {
    // 转换失败,可能涉及到类型不匹配等问题
}

static_cast

静态转换(static_cast)是最常见的一种类型转换,它在编译时进行,用于相对安全的类型转换。比如将基类指针或引用转换为派生类指针或引用。2

用于非多态类型指针的转换。可以进行各种隐式和显式转换,例如基本数据类型间、非多态之间指针和引用的转换。不会进行类型检查,因此在使用时要确保安全。

1
2
3
4
5
6
int num = static_cast<int>(3.14);

// 下面的Parent和Drive是毫不相关的两个类:
Parent* pPare = new Parent();
Drive* pDr = static_cast<Drive*>(pPare);

reinterpret_cast

重新解释转换(reinterpret_cast)是一种较为危险的类型转换,它用于将指针或引用转换为其他类型的指针或引用,甚至可以将指针和整数互相转换。因此要小心使用,可能导致未定义的行为。

1
2
int intValue = 42;
double* doublePtr = reinterpret_cast<double*>(&intValue);

const_cast

常量转换(const_cast)用于添加或移除指针或引用的const性质。需谨慎使用,避免破坏代码的一致性和安全性。

1
2
3
4
5
6
const int num = 5;
const int* ptr = &num;

int* mutablePtr = const_cast<int*>(ptr);      // 通过 const_cast 去除常量属性

*mutablePtr = 10;    // 修改常量对象的值

参考文章3

本文由作者按照 CC BY 4.0 进行授权