day17_类型转换
类型转换
- C语言风格的类型转换符
- (type)expression
- type(expression)
- C++中有4个类型转换符
- static_cast
- dynamic_cast
- reinterpret_cast
- const_cast
使用格式:xx_cast
const_cast
◼ 一般用于去除const属性,将const转换成非const
void test1const_cast() {
const Person *p1 = new Person();
Person *p2 = const_cast<Person *>(p1);
Person *p3 = (Person *)p1;
p2->m_age = 20;
p3->m_age = 30;
cout << p1->m_age << endl;
}
dynamic_cast
◼ 一般用于多态类型的转换,有运行时安全检测
void test2dynamic_cast() {
Person *p1 = new Person();
Person *p2 = new Student();
/*Student *stu1 = (Student *) p1;
Student *stu2 = (Student *) p2;
Car *car = (Car *) p2;*/
Student *stu1 = dynamic_cast<Student *>(p1);
Student *stu2 = dynamic_cast<Student *>(p2);
Car *car = dynamic_cast<Car *>(p2);
cout << stu1 << endl;
cout << stu2 << endl;
cout << car << endl;
}
static_cast
◼ 对比dynamic_cast,缺乏运行时安全检测
◼ 不能交叉转换(不是同一继承体系的,无法转换)
◼ 常用于基本数据类型的转换、非const转成const
◼ 使用范围较广
void test3static_cast() {
Person *p1 = new Person();
Person *p2 = new Student();
Student *stu1 = static_cast<Student *>(p1);
Student *stu2 = static_cast<Student *>(p2);
int i = 10;
double d = i;
cout << stu1 << endl;
cout << stu2 << endl;
}
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 *>(p2);
cout << p1 << endl;
cout << p2 << endl;
cout << p2 << endl;
cout << stu1 << endl;
cout << stu2 << endl;
cout << car << endl;