zoukankan      html  css  js  c++  java
  • c++的四种强制类型转换

      四种强制类型转换的使用形式:  cast-name<type>(expression)   //type为目标,expression为源

    1.static_cast

    1.概念

    1)static_cast用于数据类型的强制转换,只要不包含底层const,都可以使用static_cast

    2)static_cast主要的使用场景:

    static_cast在用较大类型赋值给较小类型时很有用,如把double值赋值给int,这种精度的损失,编译器会给出警告信息,但是如果使用了static_cast,则没有警告

    double b = 1.66;
    int a = static_cast<int>(b);    //此时无warning

    static_cast对于编译器无法自动执行的类型转换时也很有用

    double b = 1.66;
    void* p = &b;    //正确,任何非常量对象的地址都可以存入void*
    double* pp = p;    //错误,编译器无法自动执行这个转换
    double* pp = static_cast<double*>(p);    //正确,static_cast可以执行这个转换

    2.const_cast

    1.概念

    1)const_cast只能改变对象的底层const

    const int a = 2;
    const int* p = &a;
    int* pp = const_cast<int*>(p);    //改变底层const
    
    const char* cp = "hehe";
    char* q = static_cast<char*>(cp);    //错误,static_cast不能改变底层const
    string s = static_cast<string>(cp);    //正确,将const char*转换成string
    cout << s << endl;    //打印结果:hehe
    s = "bb";
    cout << s << endl;//打印结果:bb
    const_cast<string>(cp);    //错误,const_cast只能改变底层const

    2)const_cast常用于函数重载中

    3.reinterpret_cast

    3.1概念

    1)reinterpret_cast用来处理无关类型之间的转换,使用reinterpret_cast强制转换过程仅仅只是比特位的重新解释,因此在使用过程中需要特别谨慎

    2)reinterpret_cast主要的使用场景:

    • 改变指针或引用的类型
    • 将指针或引用转换为一个足够长度的整形
    • 将整型转换为指针或引用类型

    4.dynamic_cast

  • 相关阅读:
    WCF学习笔记
    下拉框层级绑定
    js在IE可以运行,在Firefox 不运行
    ajax 基础
    Asp.net Mvc Web Api 学习(一)
    阅读暗时间的笔记与心得
    阅读暗时间的心得与笔记
    阅读暗时间的笔记与心得(结束篇)
    阅读暗时间的笔记与心得
    阅读暗时间的心得与笔记
  • 原文地址:https://www.cnblogs.com/Joezzz/p/10439040.html
Copyright © 2011-2022 走看看