当前位置: 首页 > news >正文

C++-C++中的几种cast

文章目录

    • static_cast
      • POD类型互转
      • 任意指针类型与void*互转
      • 基类继承类之间的互转
      • 具有目标类型转换函数的类/单参数的构造函数
    • dynamic_cast
    • reinterpret_cast

static_cast

所谓static,意思是在编译期进行的转换,static_允许如下转换:

POD类型互转

int, float, bool等POD类型互转

bool a = true;
int b = static_cast<int>(a);

任意指针类型与void*互转

bool a = 123;
// int* b = static_cast<int*>(&a);  // 编译出错,static_cast不允许不相关类型指针的互转
void* p = &a;
int* b = static_cast<int*>(p);  // 通过先转为void *再转int*是可以通过编译的

基类继承类之间的互转

class Base {};
class Derived : public Base {};

Base b;
Derived* d = static_cast<Derived*>(&b);

具有目标类型转换函数的类/单参数的构造函数

class integer {
    int x;

public:
    // constructor
    integer(int x_in = 0)
        : x{ x_in }
    {
        cout << "Constructor Called" << endl;
    }

    // user defined conversion operator to string type
    operator string()
    {
        cout << "Conversion Operator Called" << endl;
        return to_string(x);
    }
};
integer obj;
string str2 = static_cast<string>(obj);  // integer类到string,通过类型转换函数
integer obj = static_cast<integer>(30);  // int到integer类,通过构造函数

dynamic_cast

dynamic与static相对,在运行时根据内存中的实际对象类型进行类型转换,用于具有虚函数的基类和子类之间的转换,通常在基类指针向下转换到派生类指针时使用。

class Base
{virtual void f() {}};
class Derived : public  Base
{
};

Base* b = new Derived;
Derived* d = static_cast<Derived*>(b);

reinterpret_cast

任意类型之间的转换,主要在底层代码中使用

bool b = true;
int* a = reinterpret_cast<int*>(b);

相关文章:

  • 大数据中的数据预处理:脏数据不清,算法徒劳!
  • Codeforces Round 1011 (Div. 2) CD
  • Spring AOP + RocketMQ 实现企业级操作日志异步采集(实战全流程)
  • linux 备份工具,常用的Linux备份工具及其备份数据的语法
  • Apache漏洞再现
  • 每日算法-250323
  • 常见中间件漏洞攻略-Weblogic篇
  • Jenkins最新版,配置Gitee私人令牌和Gitee凭证
  • 2025年中国AI搜索的行业洞察报告
  • 如何使用SystemVerilog SVA检查跨时钟域信号?
  • C++多线程编程:从创建到管理的终极指南
  • VLAN章节学习
  • 万象更新(一)VTK 坐标轴、相机方向坐标轴、立方体坐标轴
  • 基于 C++ 类的程序设计模式与应用研究
  • Python个人学习笔记(19):模块(正则表达式)
  • JVM类加载过程详解
  • 浙江大学DeepSeek公开课第二季第二期将于下周一直播!
  • 【redis】主从复制:全量复制、部分复制、实时复制详解
  • extern关键字的用法
  • 机器人的手眼标定——机器人抓取系统基础系列(五)
  • 中国人民解放军南部战区位南海海域进行例行巡航
  • 复星医药换帅:陈玉卿接棒吴以芳任董事长,吴以芳改任复星国际执行总裁
  • 绿地控股:今年一季度营业收入356亿元,中高层管理人员带头降薪
  • 证券时报:“好房子”标准即将全面落地,购房者有哪些新期待
  • 国家发展改革委:我们对实现今年经济社会发展目标任务充满信心
  • 主播说联播丨六部门出台新政!来华买买买,实惠多多多