• 类型转化


    C++有四种强制类型转化关键字:

        1. static_cast 

            用于基本类型转化,

            不可用于基本类型指针类型的转化,

            用于有继承关系的对象之间的转换,

            用于类指针之间的转化

        2. const_cast

            用于指针或引用的转化

            用于去除变量的只读属性

        3. dynamic_cast

            用于有继承关系的类指针之间的转换

            用于有交叉关系的类指针之间的转化

            具有类型检查的功能

            需要虚函数的支持

        4. reinterpret_cast

            用于指针类型间的转换

            用于指针和整形间的类型转换 

    用法: xxx_cast <Type>(Expression)

    #include <stdio.h>
    
    void static_cast_demo()
    {
        int i = 0x12345;
        char c = 'c';
        int* pi = &i;
        char* pc = &c;
        
        c = static_cast<char>(i);
        pc = static_cast<char*>(pi);  // error
    }
    
    void const_cast_demo()
    {
        const int& j = 1;             // 只读变量
        int& k = const_cast<int&>(j); // 将只读属性转化为普通变量
        
        const int x = 2;              // 真正常量
        int& y = const_cast<int&>(x); // 无法去掉常量的只读属性,已经进入了编译器的常量符号表,但编译器为常量分配了四个字节空间,y是空间的别名。
        
        int z = const_cast<int>(x);   // error
        
        k = 5;
        
        printf("k = %d
    ", k);
        printf("j = %d
    ", j);
        
        y = 8;
        
        printf("x = %d
    ", x);
        printf("y = %d
    ", y);
        printf("&x = %p
    ", &x);     // x,y地址相同
        printf("&y = %p
    ", &y);     // 
    }
    
    void reinterpret_cast_demo()
    {
        int i = 0;
        char c = 'c';
        int* pi = &i;
        char* pc = &c;
        
        pc = reinterpret_cast<char*>(pi);
        pi = reinterpret_cast<int*>(pc);
        pi = reinterpret_cast<int*>(i);
        c = reinterpret_cast<char>(i);    // error
    }
    
    void dynamic_cast_demo()
    {
        int i = 0;
        int* pi = &i;
        char* pc = dynamic_cast<char*>(pi);   //error
    }
    
    int main()
    {
        static_cast_demo();
        const_cast_demo();
        reinterpret_cast_demo();
        dynamic_cast_demo();
        
        return 0;
    }
  • 相关阅读:
    前端知识体系
    前端知识大总结(全)
    控制div层的显示以及隐藏
    让一个比较宽的banner位于页面中间
    数据结构之树(二)
    数据结构之树(一)
    数据结构之队列
    数据结构之栈
    数据结构之线性表(二)
    数据结构之线性表(一)
  • 原文地址:https://www.cnblogs.com/zsy12138/p/10686281.html
Copyright © 2020-2023  润新知