> 文章列表 > 【C/C++】C++ 四种强制转换

【C/C++】C++ 四种强制转换

【C/C++】C++ 四种强制转换

文章目录

    • 基本概念
    • 适用场景及代码案例
    • 测试运行Demo

基本概念

C++ 中有四种强制转换方式,分别是:

  1. static_cast:用于基本数据类型之间的转换,以及具有继承关系的指针或引用之间的转换。static_cast 在编译时进行类型检查,如果转换不合法则会产生编译错误。

  2. dynamic_cast:用于具有继承关系的指针或引用之间的转换,可以在运行时检查类型是否匹配。如果转换不合法,则返回空指针或引用。

  3. const_cast:用于去除指针或引用的 const 属性,可以将 const 类型转换为非 const 类型。const_cast 可以改变指针或引用的常量属性,但不能改变对象本身的常量属性。

  4. reinterpret_cast:用于不同类型之间的转换,可以将一个指针或引用转换为另一个类型的指针或引用。reinterpret_cast 不进行类型检查,因此可能会导致未定义的行为,应该谨慎使用。

需要注意的是,强制转换可能会导致数据的精度丢失或类型不匹配等问题,应该在必要的情况下使用,并且需要进行充分的测试和验证。

适用场景及代码案例

下面分别举例说明四种强制转换的使用场景:

  1. static_cast:将 int 类型转换为 double 类型。例如:

    int a = 10;
    double b = static_cast<double>(a);
    
  2. dynamic_cast:将基类指针转换为派生类指针,并检查是否转换成功。例如:

    class Base {
    public:virtual void func() {}
    };class Derived : public Base {
    public:void func() {}
    };Base* pBase = new Derived();
    Derived* pDerived = dynamic_cast<Derived*>(pBase);
    if (pDerived != nullptr) {pDerived->func();
    }
    
  3. const_cast:将 const int 类型转换为 int 类型。例如:

    const int a = 10;
    int b = const_cast<int&>(a);
    
  4. reinterpret_cast:将一个整型指针转换为一个字符型指针。例如:

    int a = 10;
    char* pChar = reinterpret_cast<char*>(&a);
    

需要注意的是,强制转换可能会导致数据的精度丢失或类型不匹配等问题,应该在必要的情况下使用,并且需要进行充分的测试和验证。

测试运行Demo

可以,下面是一个使用四种强制转换的可运行程序示例:

#include <iostream>using namespace std;int main() {// static_castint a = 10;double b = static_cast<double>(a);cout << "static_cast: " << b << endl;// dynamic_castclass Base {public:virtual void func() {}};class Derived : public Base {public:void func() {}};Base* pBase = new Derived();Derived* pDerived = dynamic_cast<Derived*>(pBase);if (pDerived != nullptr) {cout << "dynamic_cast: success" << endl;pDerived->func();} else {cout << "dynamic_cast: failed" << endl;}// const_castconst int c = 20;int d = const_cast<int&>(c);cout << "const_cast: " << d << endl;// reinterpret_castint e = 30;char* pChar = reinterpret_cast<char*>(&e);cout << "reinterpret_cast: " << *pChar << endl;return 0;
}

该程序使用了四种强制转换方式,分别将 int 类型转换为 double 类型、将基类指针转换为派生类指针并检查是否转换成功、将 const int 类型转换为 int 类型、将一个整型指针转换为一个字符型指针。运行程序后,输出结果如下:

static_cast: 10
dynamic_cast: success
const_cast: 20
reinterpret_cast: 

其中,reinterpret_cast 的输出结果可能因为字符编码的不同而有所不同。