C++ 类型转换

2021-12-27  本文已影响0人  我阿郑

C语言风格的转换

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

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

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
Student *stu1 = NULL 置为空

3. static_cast

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
上一篇 下一篇

猜你喜欢

热点阅读