c++(10)-类型转换

    C编译器无法保证强制类型转换的正确性。

    C++强制类型转换分4种类型:

强制类型转换

static_castconst_cast
dynamic_castreinterpret_cast

static_cast

  • 用于基本类型间的转换
  • 不能用于基本类型指针间的转换
  • 可用于有继承关系类对象间的转换和类指针间的转换

const_cast

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

reinterpret_cast

  • 用于指针类型间的强制转换
  • 用于整数指针类型间的强制转换

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);    //static_cast可用于基本类型间的转换
   // pc = static_cast<char*>(pi); //error,static_cast不能用于基本类型指针间的转换
}

void const_cast_demo()
{
    const int& j = 1;   //只读变量
    int& k = const_cast<int&>(j); //const_cast可用于去除变量的只读属性
    
    const int x = 2; 	//常量
    int& y = const_cast<int&>(x); //编译器还是会为常量x在内存空间中分配内存,y就是这片内存的别名
    
   // int z = const_cast<int>(x); //error,const_cast目标类型必须是指针或引用
    
    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);  //reinterpret_cast可用于指针类型间的强制转换
    pi = reinterpret_cast<int*>(pc);
    pi = reinterpret_cast<int*>(i);    //reinterpret_cast可用于整数和指针类型间的强制转换
   // c = reinterpret_cast<char>(i);  //error,reinterpret_cast不能用于基本类型间的转换
}

/*dynamic_cast_demo:
 * -用于有继承关系的类指针间的转换
 * -用于有交叉关系的类指针间的转换
 * -具有类型检查的功能
 * -需要虚函数支持
 */
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;
}

 

093416_CVuu_3472252.png

转载于:https://my.oschina.net/u/3472252/blog/917902

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值