类型转换
1. 介绍
-
C语言风格的类型转换符:
(type)expression
type(expression)
-
C++中有4个类型转换符:
static_cast
dynamic_cast
reinterpret_cast
const_cast
-
使用格式:
xx_cast<type>(expression)
2. const_cast
- 一般用于去除
const
属性,将const
转换成非const
;
const Person *p1 = new Person();
p1->m_age = 10;
Person *p2 = const_cast<Person *>(p1);
p2->m_age = 20;
3. dynamic_cast
- 一般用于多态类型的转换,有运行时安全检测;
class Person {
virtual void run() { }
};
class Student : public Person { };
Class Car { };
Person *p1 = new Person();
Person *p2 = new Student();
Student *stu1 = dynamic_cast<Student *>(p1); // NULL
Student *stu2 = dynamic_cast<Student *>(p2);
Car *car = dynamic_cast<Car *>(p1); // NULL
4. static_cast
- 对比
dynamic_cast
,缺乏运行时安全检测; - 不能交叉转换(不是同一继承体系的,无法转换);
- 常用于基本数据类型的转换、非
const
转成const
; - 使用范围较广。
Person *p1 = new Person();
Person * p2 = new Student();
Student *stu1 = static_cast<Student *>(p1);
Student *stu2 = static_cast<Student *>(p2);
Car *car = static_cast<Car *>(p1);
5. reinterpret_cast
- 属于比较底层的强制转换,没有任何类型检查和格式转换,仅仅是简单的二进制数据拷贝;
- 可以交叉转换;
- 可以将指针和整数互相转换。
Person *p1 = new Person();
Person *p2 = new Person();
Student *stu1 = reinterpret_cast<Student *>(p1);
Student *stu2 = reinterpret_cast<Student *>(p2);
Car *car = reinterpret_cast<Car *>(p1);
int *p = reinterpret_cast<int *>(100);
int num = reinterpret_cast<int>(p);
int i = 10;
double d1 = reinterpret_cast<double &>(i);