C++强制类型转换

在 C++ 中,主要有四种类型的显式类型转换(强制类型转换)运算符:

  1. static_cast
  2. dynamic_cast
  3. const_cast
  4. reinterpret_cast

1. static_cast

  static_cast 用于在编译时执行显式类型转换。它可以用于大多数类型转换,如基本数据类型之间的转换、指针和引用之间的转换、类层次结构中的上行转换和下行转换(但不检查下行转换的安全性)。

1.1 语法:

static_cast<new_type>(expression)

 1.2 示例:

#include <iostream>

int main() {
    // 基本数据类型转换
    int i = 10;
    double d = static_cast<double>(i);
    std::cout << "d: " << d << std::endl; // 输出: d: 10.0

    // 类层次结构中的上行转换
    class Base {};
    class Derived : public Base {};

    Derived derived;
    Base* base = static_cast<Base*>(&derived);

    // 基本数据类型转换指针
    void* void_ptr = static_cast<void*>(&i);
    int* int_ptr = static_cast<int*>(void_ptr);
    std::cout << "*int_ptr: " << *int_ptr << std::endl; // 输出: *int_ptr: 10

    return 0;
}

2. dynamic_cast

  dynamic_cast 主要用于在类层次结构中进行安全的下行转换(从基类指针或引用转换为派生类指针或引用)。它在运行时进行类型检查,如果转换不安全,将返回 nullptr(对于指针)或抛出 std::bad_cast 异常(对于引用)。

2.1 语法

dynamic_cast<new_type>(expression)

2.2 示例

#include <iostream>
#include <typeinfo>

class Base {
public:
    virtual ~Base() {} // 必须有虚函数以启用 RTTI
};

class Derived : public Base {};

class Unrelated {};

int main() {
    Base* base = new Derived;
    Derived* derived = dynamic_cast<Derived*>(base);

    if (derived) {
        std::cout << "dynamic_cast 成功" << std::endl;
    } else {
        std::cout << "dynamic_cast 失败" << std::endl;
    }

    base = new Base;
    derived = dynamic_cast<Derived*>(base);

    if (derived) {
        std::cout << "dynamic_cast 成功" << std::endl;
    } else {
        std::cout << "dynamic_cast 失败" << std::endl;
    }

    delete base;
    return 0;
}

3. const_cast

  const_cast 用于移除对象的 const 和 volatile 属性。它只能改变属性,不能用于其他类型转换。

3.1 语法

const_cast<new_type>(expression)

3.2 示例

#include <iostream>

void print(const int* p) {
    // 使用 const_cast 移除 const 属性
    int* modifiable = const_cast<int*>(p);
    *modifiable = 20;
    std::cout << "修改后的值: " << *p << std::endl;
}

int main() {
    int i = 10;
    print(&i); // 输出: 修改后的值: 20
    return 0;
}

4. reinterpret_cast

  reinterpret_cast 进行低级别的位模式转换。它几乎可以转换任何类型的数据,但非常危险,不建议经常使用。使用不当可能导致未定义行为。 

4.1 语法

reinterpret_cast<new_type>(expression)

4.2 示例

#include <iostream>

int main() {
    int i = 65;
    char* ch = reinterpret_cast<char*>(&i);
    std::cout << "字符值: " << *ch << std::endl; // 输出: 字符值: A

    return 0;
}

5. 总结

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值