大话C++之:类型转换

C++中4种不同的类型转换

在 C++ 中,有四种主要的类型转换操作符:static_castdynamic_castconst_castreinterpret_cast。每种转换操作符都适用于不同的场景:

1. static_cast

适用场景:用于各种基本类型转换,基本类型包括int, uint8_t, enum等,但以下3种情况除外:

  • 指针:只能通过dynamic_cast或者是reinterpret_cast
  • const转非const:只能通过const_cast
  • volatile转非volatile: 只能通过const_cast

示例

  • 将浮点数转换为整数。
    float f = 3.5;
    int i = static_cast<int>(f);  // i 的值为 3
    
  • 将整数转换为枚举类型。
    enum Color { RED, GREEN, BLUE };
    int n = 1;
    Color color = static_cast<Color>(n);  // color 是 GREEN
    

2. dynamic_cast

适用场景:主要用于基类指针/引用派生类指针/引用的相互转换。如果转换的双方不存在继承关系,会返回nullptr

示例

  • 在类的继承关系中转换类型。
    class Base { virtual void dummy() {} };
    class Derived : public Base { int a; };
    
    Base *b = new Derived;
    Derived *d = dynamic_cast<Derived*>(b);
    

3. const_cast

适用场景:用于修改类型的constvolatile属性,可以给某个对象加上/移除const或者volatile属性。不过一般用于移除对象的const属性。

不知道volatile关键字的作用?移步这里大话C++之:volatile关键字,5分钟讲明白😁

示例

  • 从一个常量对象移除const限定。
    const int x = 10;
    int* modifiable = const_cast<int*>(&x);
    *modifiable = 20;  // 不推荐这样做,可能会导致未定义行为
    

4. reinterpret_cast

适用场景:前3种转换方法无法满足时,使用reinterpret_castreinterpret_cast等价于C语言里的强制类型转换,可以随意转换。

示例

  • 将指针类型转换为足够大的整数类型。
    char *p = new char[10];
    std::size_t addr = reinterpret_cast<std::size_t>(p);
    

总结

  • static_cast 是最常用的类型转换,适用于基本类型之间的转换。
  • dynamic_cast 主要用于基类指针或引用派生类指针或引用之间的转换 。
  • const_cast 用于修改或移除对象的constvolatile属性。
  • reinterpret_cast 等效于C语言里强制类型转换。
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值