新型类型装换

强制类型装换

  • C语言强类型转换
    • (type) (Expression)
    • 强制类型转换会照成内存截断,数据丢失
    • 任何类型间都能装换
    • 难于定位
  • C++强制类型装换(记住****)
    • static_cast
      • 基本类型转换
      • 不能用于基本类型指针间转换
      • 用于有继承关系类对象之间的转换和类指针之间的转换
    • const_cast
      • 用于去除变量的只读属性
      • 范围目标类型必须是指针或引用
    • reinterpret_case
      • 用于指针类型间的强制转换
      • 整数和指针类型间的强制转换
    • dynamic_cast
      • 用于有继承关系的类指针间的转换
      • 用于有交叉关系的类指针间的转换
      • 具有类检查
      • 需要虚拟函数的支持
#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); //不能用于基本类型指针间转换
	pc = reinterpret_cast<char*>(pi);
} 

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);//const_cast只能用于引用和指针强转
    
    k = 5;
    
    printf("k = %d\n", k);//5
    printf("j = %d\n", j);//5
    
    y = 8;
    
    printf("x = %d\n", x);//8 x    ----   2
    printf("y = %d\n", y);//8
    printf("&x = %p\n", &x);//
    printf("&y = %p\n", &y);//不同地址  X ----  与上面地址相同
}

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); //不能用于基本类型之间
}

void dynamic_cast_demo()
{
    int i = 0;
    int* pi = &i;
    //char* pc = dynamic_cast<char*>(pi);//类 虚拟函数
}

int main()
{
    static_cast_demo();
    const_cast_demo();
    //reinterpret_cast_demo();
    //dynamic_cast_demo();
    
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值