类型转化

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\n", k);
    printf("j = %d\n", j);
    
    y = 8;
    
    printf("x = %d\n", x);
    printf("y = %d\n", y);
    printf("&x = %p\n", &x);     // x,y地址相同
    printf("&y = %p\n", &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;
}

 

posted @ 2019-04-10 21:35  张不源  Views(174)  Comments(0Edit  收藏  举报