• 类型转换


    • 隐式类型转换
    • 强制类型转换
    • 静态类型转换
    • 动态类型转换
    • 常类型转换
    • 重解释类型转换

    隐式类型转换

    不同类型数据之间进行赋值

    函数调用时,不同类型实参到形参的传值

    函数返回了与定义类型不同的数据

    //.h int a = 'c';//char类型隐形转换为int类型 void func(int a) { cout << "abc" <隐式转换 char funcT(int b) { return b;//返回类型隐式转换 }

    强制类型转换

    在类型不兼容时,可使用强制类型转换,在两个不同的类型之间完成转换。实现简单,转换功能强大。但由于时强制转换,可能会导致不合理转换,使用会引起各种错误,很危险,慎用~

    char ch = 'a'; int b = (int)ch; 或 int b = int(ch);

    静态类型转换

    static_cast

    目标类型变量 = static_cast (源类型变量);

    常用于将void* 转换为其它类型的指针

    1. int* pi = NULL;
    2. void* pv = pi;
    3. pi = static_cast<int*>(pv);

    动态类型转换

    dynamic_cast

    目标类型变量 = dynamic_cast(源类型变量);

    用于类继承层次间的指针或引用转换,支持运行时识别指针或引用。主要是用于安全的向下转型。

    1. TBaseCast* baseCast;
    2. TDerived* der = new TDerived();
    3. baseCast = dynamic_cast(der);//向上转型本来就是安全的
    4. //baseCast = der;
    5. TBaseCast* baseCast2 = new TBaseCast();
    6. TDerived *der2 = dynamic_cast(baseCast2);//向下转型

    常类型转换

    const_cast

    目标类型变量 = const_cast(源类型变量);

    用于去除指针或引用的属性

    通过const_cast运算符,也只能将const type转换为type,将const type&转化为type&。

    1. const int ci = 80;
    2. int* pci = const_cast<int*>(&ci);// const转换为非const

    重解释类型转换

    reinterpret_cast

    目标类型变量 = reinterpret_cast(源类型变量);

    用于任意类型指针或引用之间的转换

    指针和整数之间的转换

    用来处理无关类型之间的转换;它会产生一个新值,这个值会有与原始参数完全相同的比特位。其实就是按比特位重新解释为要转换的类型。

    1. struct T { char type[5];
    2. char acc[9]; char passwd[7]; };
    3. char buf[] = "0001\00012345678\000123456";
    4. T * pt = reinterpret_cast(buf);//把字符流转化为结构体
    5. cout << pt->type << endl;
    6. cout << pt->acc << endl;
    7. cout << pt->passwd << endl;

  • 相关阅读:
    Keil 无法烧写程序
    Ansys(Maxwell、Simplorer)与Simulink联合仿真入门
    Android Retrofit 封装模版
    【UE5 C++基础 04】UHT基础
    Python 安装CSF(布料模拟滤波)的环境配置
    DocumentType类型
    【Django | 开发】分离上线环境与开发环境(多settings配置)
    ChatGPT - 在ChatGPT中设置通用提示模板
    Spring概述
    计算机毕业设计Java无人售货机管理系统(源码+系统+mysql数据库+Lw文档)
  • 原文地址:https://blog.csdn.net/rbyyy924805/article/details/127722162