美文网首页
C++ 类型转换

C++ 类型转换

作者: 我阿郑 | 来源:发表于2021-12-27 11:01 被阅读0次

C语言风格的转换

int a = 10;
double d = (double)a;
double d2 = double(a);

C++ 中有4个类型转换符

  • static_cast
  • dynamic_cast
  • reinterpret_cast
  • const_cast

1. const_cast

一般用于去除const属性,将const转换成非const

const Person *p1 = new Person();
p1->m_age = 10;

// 将`const`转换成`非const`
Person *p2 = const_cast<Person *>(p1);
p2->m_age = 20;

2. dynamic_cast

一般用于多态类型的转换,有运行时的安全检测

image.png
  • dynamic_cast 会做类型安全检测,将p1 强制转换成子类Student明显是不安全的,当dynamic_cast<Student *>(p1) ,检测到这种操作不安全就会将
Student *stu1 = NULL 置为空

3. static_cast

  • 对比dynamic_cast, 缺乏运行时安全检测
  • 不能交叉互换
  • 常用与基本数据类型的转换,非const转const
int a = 10;
double d = a;
等价于
int a = 10;
double d = static_cast<double> (a);

// 非const转换成const

Person *p1 = new Person();
const Person *p2 = static_cast<const Person *>(p1);

4.reinterpret_cast

属于比较底层的强制转换,没有任何类型检查和格式转换,仅仅是简单的二进制数据拷贝

Person *p1 = new Person();
Person *p2 = new Student();

Student *stu1 = reinterpret_cast<Student *>(p1);
Student *stu2 = reinterpret_cast<Student *>(p2);
Car *car = reinterpret_cast<Car *>(p1);

// int 转int 不需要&
int *p = reinterpret_cast<int *>(100);
int num = reinterpret_cast<int>(p);

// int 转 double, 需要加&
int i = 10;
doble d1 = reinterpret_cast<doble &>(i);
  • 直接将右边的内容拷贝到左边的存储空间
// int i = 10;
int *p = reinterpret_cast<int *>(0x100);

接着,可以通过int a = (int)p 将值取出来赋给a,也可以

int a = reinterpret_cast<int>(p);

objc源码举例:

image.png

相关文章

网友评论

      本文标题:C++ 类型转换

      本文链接:https://www.haomeiwen.com/subject/gujkqrtx.html