zoukankan      html  css  js  c++  java
  • C++强制类型转换

      C++中的强制类型转换虽然兼容C语言中的强制类型转换,但是不建议在C++中使用C语言风格的强制类型转换。C++中的强制类型转换共有4种:static_cast,dynamic_cast、const_cast、reinterpret_cast.

    static_cast

    1. 使用格式

      进行编译期间的类型检查

      type1 a;

      type2 b = static_cast<type1>(a);

    2. 使用范围

      (1)基本数据类型之间的转换,如int->double;

        int a = 6;

        double b = static_cast<int>(a);

      (2)派生体系中向上转型:将派生类指针或引用转化为基类指针或引用

    dynamic_cast

      (1)执行派生类指针或引用与基类指针或引用之间的转换。

      (2)使用多态的场景,增加了一层对真实调用对象类型的检查,可以实现向上转型和向下转型,前提是必须使用public或protected继承

      (3)dynamic_cast不是强制转换,而是带有某种”咨询“性质的,如果不能转换,返回NULL。这是强制转换做不到的。

    const_cast

      (1)去除const常量属性,使其可以修改

    reinterpret_cast

      仅仅是复制n1的比特位到d_r, 没有进行必要的分析.interpret_cast是为了映射到一个完全不同类型的意思,这个关键词在我们需要把类型映射回原有类型时用到它。我们映射到的类型仅仅是为了故弄玄虚和其他目的,这是所有映射中最危险的。(这句话是C++编程思想中的原话。

    #include <iostream>
    #include <cstdio>
    #include <string>
    
    using namespace std;
    
    class A {
        public:
        A(){};
        int m_a;
    };
    
    class B {
        public:
        int m_b;
    };
    
    class C : public A, public B {};
    
    int main()
    {
        const A a;
        //a.m_a= 1;
        const_cast<A&>(a).m_a = 2;
        //a.m_a= 3;编译不能通过,说明const_cast只能转换一次,不是永久脱离原有const属性
        cout<<a.m_a<<endl;
        int n = 9;
        double d_s = static_cast<double>(n);
        double d_r = reinterpret_cast<double&>(n);
        cout<<d_r<<endl;//4.24399e-314
        //在进行计算以后, d_r包含无用值. 这是因为 reinterpret_cast
         仅仅是复制n1的比特位到d_r, 没有进行必要的分析.interpret_cast是为了映射到一个完全不同类型
         的意思,这个关键词在我们需要把类型映射回原有类型时用到它。我们映射到的类型仅仅是为了故弄
         玄虚和其他目的,这是所有映射中最危险的。(这句话是C++编程思想中的原话
    
        C c;
        printf("%p, %p, %p
    ", &c, reinterpret_cast<B*>(&c), static_cast <B*>(&c));
        //前两个的输出值是相同的,最后一个则会在原基础上偏移4个字节,这是因为static_cast计算了父子类指针转换的偏移量,
        并将之转换到正确的地址(c里面有m_a,m_b,转换为B*指针后指到m_b处),而reinterpret_cast却不会做这一层转换
        因此, 你需要谨慎使用 reinterpret_cast.
    
    
        return 0;
    }
  • 相关阅读:
    [Angular] Architectures for Huge Angular Based Enterprise
    [Bash] Move and Copy Files and Folders with Bash
    [Bash] Create nested folder in Bash
    [Bash] View Files and Folders in Bash
    [Angular] Expose Angular Component Logic Using State Reducers
    [Angular] Modify User Provided UI with Angular Content Directives
    [Angular] Refactor Angular Component State Logic into Directives
    [Angular] Communicate Between Components Using Angular Dependency Injection
    [Angular] Write Compound Components with Angular’s ContentChild
    java web从零单排第二十一期《Hibernate》主键的生成方式,用户增加与显示用户列表
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/8888099.html
Copyright © 2011-2022 走看看