C++学习笔记 第11课 新型类型转换

1.c语言方式的类型转换

(类型)(变量)
如:

int i = 5;
char c= 4;
i=(int)c;

1.1编程实验

test.c

#include <stdio.h>
typedef void(PF)(int);
struct Point
{
   int x;
   int y;
};
int main()
{
   int v = 0x12345;
   PF* pf = (PF*)v;
   char c = char(v);
   Point* p = (Point*)v;
   
   pf(5);
   
   printf("p->x = %d\n", p->x);
   printf("p->y = %d\n", p->y);
   return 0;
}

结果:发生异常
在这里插入图片描述

1.2 c方式类型转换存在问题

  1. 过于粗暴:任意类型之间都可以进行转换,编译器很难判断其正确性
  2. 难于定位:在源码中无法快速定位所有使用轻质类型转换的语句

1.3 问题:强制类型转换在实际工程中是很难完全避免的!如何进行更加安全可靠的转换

  • 优化C的方法
  • 新式类型转换

2.C++中新式类型转换

在c++中将强制类型转换分为四种不同的类型

static_cast
const_cast
dynamic_cast
reinterpret_cast

用法:

xxx_cast<类型>

2.1 用法

1.static_cast

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

编程实验:

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
}

2.const_cast

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

编程实验:


void cast_demo()
{
    const int& j = 1;
    int& k = const_cast<int&>(j);

    const int x = 2;
    int& y = const_cast<int&>(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);
   
}


int main()
{
    cast_demo();
    return 0;
}
结果:
k = 5
j = 5
x = 2
y = 8
&x = 00A9F724
&y = 00A9F724

3.dynamic_cast

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

编程实验:


void dynamic_cast_demo()
{
    int i = 0;
    int* pi = &i;
    //char* pc = dynamic_cast<char*>(pi); //错误,类型不同
}

int main()
{
    dynamic_cast_demo();
    return 0;
}

4.reinterpret_cast(重解释)

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

编程实验:

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, 非整数与指针转换
}

int main()
{
    reinterpret_cast_demo();
    return 0;
}

3.总结

C方式的强制类型转换过于粗暴,潜在的问题不易被发现,不易在代码中定位新式类型转换以C++关键字的方式出现,编译器能够帮助检查潜在的问题,非常方便的在代码中定位,支持动态类型识别(dynamic_cast)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值