简介
C++语言级别提供的四种类型转换方式,都是模板
const_cast
:去掉(指针或引用)常量属性的类型转换,编译时期类型转换static_cast
: 提供编译器认为的安全的类型转换,用的最多reinterpret_cast
: 类似于C风格的强转dynamic_cast
:主要用在继承结构中,可支持RTTI
类型识别的上下转换。运行时期的类型转换
const_cast
const_cast
只能调节限定符类型,不能更改基础类型;
const int a = 10;
double* p1 = (double*)&a;
int* p3 = const_cast<int*>(&a); // ok
char* p2 = const_cast<char*>(&a); // error
const_cast
中类型只能是引用或指针类型
const int a = 10;
int b = const_cast<int>(a); //eroor
static_cast
// 基类类型 和 派生类类型可用 static_cast
int a = 10;
char b = static_cast<int>(a); // OK
int* p = nullptr;
// 如果int *转short *成功最后访问的空间本应是4B而变为1B
double* b = (double*)p; // ERROR
short* b = static_cast<short*>(p); // ERROR
reinterpret_cast
reinterpret_cast 类似于C得强制类型转换
int* p = nullptr;
double* b = reinterpret_cast<double*>(p); // OK,但不安全
dynamic_cast
关注注释
class Base
{
public:
virtual void func() = 0;
};
class Derive1 : public Base
{
public:
void func() { cout << "call Derive1::func" << endl; }
};
class Derive2 : public Base
{
public:
void func() { cout << "call Derive2::func" << endl; }
// Derive2实现新功能的API接口函数
void derive02func()
{
cout << "call Derive2::derive02func" << endl;
}
};
void showFunc(Base* p)
{
// 实现若传给p的是 Derive2 对象就调用其 derive02func 函数
// dynamic_cast会检查p是否指向的是 Derive2 对象
// p->vfptr->vftable->RTTI信息,若是,dynamic_cast类型转换成功
// 返回 Derive2对象地址给pd2,否则返回nullptr
// dynamic_cast称为运行时期类型转换,static_cast编译时期的类型转换
Derive2* pd2 = dynamic_cast<Derive2*>(p);
if (pd2 != nullptr)
{
pd2->derive02func();
}
else
{
p->func(); // 动态绑定
}
}
int main()
{
Derive1 d1;
Derive2 d2;
showFunc(&d1);
showFunc(&d2);
return 0;
}
输出结果
若将其中的dynamic_cast
替换为static_cast
,则不论 Derive1
还是 Derive2
的对象都转换为Derive2*