ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++中的强制类型转换

2019-09-15 12:00:10  阅读:229  来源: 互联网

标签:类型转换 const reinterpret int C++ cast 强制 pi


在C语言中,强制类型转换的方式为(Type)Expression,另外还有一种现在已经不用的旧式写法Type(Expression),这两种方式是等价的。

但是,C语言的强制类型转换方式存在一些问题:

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

然而,强制类型转换在实际工程中几乎是不可避免的,为此C++将强制类型转换分为4种不同的类型,以提供更加安全可靠的转换。

强制类型转换 说 明
static_cast 用于基本类型之间、有继承关系的类对象之间、类指针之间的转换
不能用于基本类型指针之间的转换
const_cast 用于去除变量的只读属性
强制转换的目标类型必须是指针或引用
reinterpret_cast 用于指针类型之间、整数和指针类型之间的转换
dynamic_cast 用于有继承关系的类指针之间、有交叉关系的类指针之间的转换
具有类型检查的功能
需要虚函数的支持

C++提供的4种强制类型转换以关键字的方式出现,使用语法为:xxx_cast<Target 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,static_cast不能用于基本类型指针间的转换
}

void const_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,const_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,reinterpret_cast不能用于基本类型间的转换
}

void dynamic_cast_demo()
{
    int i = 0;
    int *pi = &i;
    char *pc = dynamic_cast<char *>(pi); // Error,dynamic_cast只能用于有继承关系或交叉关系的类指针间的转换,且类中必须有虚函数
}

int main()
{
    static_cast_demo();
    const_cast_demo();
    reinterpret_cast_demo();
    dynamic_cast_demo();

    return 0;
}

可以看出,使用新的强制类型转换

  • 在编译时能够帮助检查潜在的问题
  • 搜索4个关键字,可以非常方便在代码中定位

标签:类型转换,const,reinterpret,int,C++,cast,强制,pi
来源: https://www.cnblogs.com/songhe364826110/p/11521589.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有