1 四种方法概括
方法 | 使用场景 |
---|---|
static_cast | 一般的转换 |
dynamic_cast | 通常在积累和派生类之间的转换中使用 |
const_cast | 主要针对const的转换 |
reinterpret_cast | 用于没有任何关联对象之间的转换,慎用! |
2 static_cast的用法
适用范围:内置数据类型以及具有继承关系的指针或者引用
#include <iostream>
class People {};
class Animal {};
class Cat: public Animal {};
void test01()
{
//1.基础数据转换
int a = 97;
char b = static_cast<char>(a);
std::cout << b << '\n';
//2.具有继承关系的指针或者引用
//错误:没有继承关系
//People* people = nullptr;
//Animal* ani = static_cast<People*>(people);
Animal* ani = nullptr;
Cat* cat = static_cast<Cat*>(ani);
Cat* cat = nullptr;
Animal* ani = static_cast<Animal*>(cat);
Animal obj_ani;
Animal& ani_ref = obj_ani;
Cat& cat_ref = static_cast<Cat&>(ani_ref);
Cat obj_cat;
Cat& cat_ref = obj_cat;
Animal& cani_ref = static_cast<Animal&>(obj_cat);
}
int main()
{
test01();
}
3 dynamic_cast的用法
使用范围:转换具有继承关系的指针或引用,转换前会进行对象的数据类型检查
注意:只能将子类指针转成父类指针(从大到小),不能将父类指针转成子类指针
#include <iostream>
class People {};
class Animal {};
class Cat: public Animal {};
void test02()
{
// 错误代码
// Animal* ani = nullptr;
// Cat* cat = dynamic_cast<Cat*>(ani);
Cat* cat = nullptr;
Animal* ani = dynamic_cast<Animal*>(cat);
Cat obj_cat;
Cat& cat_ref = obj_cat;
Animal& ani_ref = dynamic_cast<Animal&>(cat_ref);
}
int main()
{
test02();
}
4 const_cast的用法
适用范围:去除或者增加对象的const属性,可以为指针,引用和对象指针
#include <iostream>
void test03()
{
int a = 10;
const int& b = a;
int& c = const_cast<int&>(b);
c = 20;
std::cout << "a = " << a << std::endl; // 20
std::cout << "b = " << b << std::endl; // 20
std::cout << "c = " << c << std::endl; // 20
const int* p = nullptr;
int* p1 = const_cast<int*>(p);
int* p2 = nullptr;
const int* p3 = const_cast<const int*>(p2);
}
int main()
{
test03();
}
5 reinterpret_cast的用法
适用范围:强制类型转换,无关的指针类型或者函数指针都可以转换
#include <iostream>
class People {};
class Animal {};
typedef void(fun1)(int, int);
typedef int(fun2)(int, char*);
void test04()
{
//1.无关的指针类型可以转换
People* people = nullptr;
Animal* ani = reinterpret_cast<Animal*>(people);
//2.函数指针转换
fun1* f1;
fun2* f2 = reinterpret_cast<fun2*>(f1);
}
int main()
{
test04();
}