第11课.新型的类型转换

早过忘川 提交于 2019-12-03 11:02:13

1.新型类型转换

c++将强制类型转换分为4种不同的类型
static_cast
const_cast
dynamic_cast
reinterpret_cast
用法:

xxx_cast<Type>(Expression)

static_cast

a.用于基本类型间的转换
b.不能用于基本类型指针间的转换
c.用于有继承关系类对象之间的转换和类指针之间的转换

const_cast

a.用于去除变量的只读属性
b.强制转换的目标类型必须是指针或引用

reinterpret_cast

a.用于指针类型间的强制转换
b.用于整数和指针类型间的强制转换

dynamic_cast

a.用于有继承关系的类指针间的转换
b.用于有交叉关系的类指针间的转换
c.具有类型检查的功能
d.需要虚函数的支持

#include <stdio.h>

void static_cast_demo()
{
    int i = 0x12345;
    char c = 'c';
    int* pi = &i;
    char* pc = &c;
    
    c = static_cast<char>(i);       //int型的i转化为char型,赋值给c
    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);    //这里去掉的是地址的只读属性,不是进入符号表的x的只读属性
    
    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);
    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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!