C++几种cast该如何使用

在C++中,有四种主要的类型转换(cast)方法:

1. Static Cast(静态转换)

  • 用法static_cast<new_type>(expression)

  • 情况:用于基本数据类型之间的转换,例如将整数转换为浮点数,或者将指针或引用从一个类型转换为另一个类型,但是需要注意,它在运行时不提供任何检查。

    int intValue = 10;
    double doubleValue = static_cast<double>(intValue);

2. Dynamic Cast(动态转换)

  • 用法dynamic_cast<new_type>(expression)

  • 情况:主要用于基类和派生类之间的指针或引用转换。只能在涉及多态类(至少有一个虚函数)的情况下使用。在运行时,会检查是否可以安全地进行转换。

    class Base {
    public:
    virtual ~Base() {}
    };

    class Derived : public Base {};

    Base* basePtr = new Derived();
    Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);

    if (derivedPtr) {
    // 转换成功
    } else {
    // 转换失败
    }

3. Const Cast(常量转换)

  • 用法const_cast<new_type>(expression)

  • 情况 :用于添加或删除变量的const属性。这通常用于函数中,其中参数被声明为const,但在函数内部需要修改。

    const int constValue = 42;
    int* nonConstPtr = const_cast<int*>(&constValue);
    *nonConstPtr = 100; // 合法,但是潜在的未定义行为

4. Reinterpret Cast(重新解释转换)

  • 用法reinterpret_cast<new_type>(expression)

  • 情况:用于对指针或引用进行不安全的低级别转换,通常用于处理底层的二进制数据。这是最危险的转换,因为它不执行类型检查。

    int intValue = 42;
    void* voidPtr = reinterpret_cast<void*>(&intValue);

在选择类型转换时,应该根据具体的情况和需求谨慎选择合适的转换方式,避免不必要的安全问题。

相关推荐
blasit18 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
哇哈哈20216 天前
信号量和信号
linux·c++
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马6 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc6 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法