当前位置: 移动技术网 > IT编程>开发语言>C/C++ > 5.C++里的4种新型类型转换

5.C++里的4种新型类型转换

2018年02月21日  | 移动技术网IT编程  | 我要评论

河马家老总,香港中华之声通讯社,mmpp

1首先来回顾C的强制转换

大家都知道,在编译C语言中的强制转换时,编译器不会检查转换是否成功,都会编译正确.

比如:

#include "stdio.h"

struct Position
{
int x;
int y;
};

int main()
{
 int i;
 struct Position *p;

 i=0x123456;

 p=(struct Position *)i;

 printf("px=%d,py=%d\n",p->x,p->y);
}

 输出结果如下图所示:

 

从上图可以看到,只有当运行代码时,才会出现段错误问题.

C代码上千行,若出现这种问题,是非常难找的.

 

2.C++的新型类型转换

所以在C++,便引入了4强制类型转换

2.1 static_cast(静态类型转换)

  • 用于基本数据类型之间的转换(char,int,const int)
  • 不能用于基本数据类型指针之间的转换(char *,int *)
  • 用于有继承关系类对象之间的转换
  • 用于类指针之间的转换

例如:

    int i = 0x45;

    char c = 'c';

    c = static_cast<char>(i);    
    //char* pc = static_cast<char*>(&i);   //此行错误,不能用于基本指针之间转换

 

 

2.2 const_cast(去常类型转换)

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

例如:

const int x =1;     //const:定义一个常量x 

const int& j =2;    //const引用:定义一个只读变量j

int& p1= const_cast<int&>(x);   //强制转换int &

int *p2 = const_cast<int*>(&j);  //强制转换int*

//int p3 = const_cast<int>(j);    //此行错误,不能转换普通数据型

p1=3;
*p2=4;

printf("x=%d,   j=%d\n",x,j);
printf("p1=%d  *p2=%d\n",p1,*p2);

输出结果:

x=1   j=4

p1=3  *p2=4

从输出结果,可以看出修改p1,p2,只有j内容变换了,是因为变量jconst引用定义的,所以是个只读变量.

 

2.3 dynamic_cast(动态类型转换)

  • 用于有继承关系的类指针间的转换
  • 用于有交叉关系的类指针间的转换
  • 具有类型检查的功能
  • 需要虚函数的支持
  • 不能用于基本数据类型指针之间的转换(char *,int *)

 

2.4 reinterpret_ cast(解读类型转换)

  • 用于所有指针的强制转换

(解读是指:对要转换的数据进行重新的解读)

例如:

    int i = 0;

    char j='c';
int   *p1=reinterpret_cast<int *>(&i);

    char  *p2=reinterpret_cast<char *>(&j);

    //int  p3=reinterpret_cast<int >i;  //此行错误,不能转换普通数据型

 

 

 

    

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网