前言
C++中提供了四种显式的类型转换方法:static_cast,const_cast,reinterpret_cast,dynamic_cast.下面分别看下它们的使用场景。
显式类型转换
1.staitc_cast
这是最常用的,一般都能使用,除了不能转换掉底层const属性。
#include
using namespace std;
int main()
{
?cout << "static_cast转换演示" << endl;
?int i = 12, j = 5;
?//对普通类型进行转换
?double res = static_cast(i) / j;
?cout << "res = "<< res << endl;
?float f = 2.3;
?void *pf = &f;
?//把void*转换为指定类型的指针
?float *ff = static_cast(pf);
?cout << "*ff = " << *ff << endl;
?/*
?int cd = 11;
?const int *pcd = &cd;
?int *pd = static_cast(pcd);? //error static_const 不能转换掉底层const
?*/
?cin.get();
?return 0;
}
运行

对于变量的const属性分为两种:顶层的、底层的。对于非指针变量而言两者的意思一样。对于指针类型则不同。如int *const p;? ? p的指向不可改变,这是顶层的;
const int *p;? ? p指向的内容不可改变,这是底层的。
2.const_cast
用法单一,只用于指针类型,且用于把指针类型的底层const属性转换掉。
#include
using namespace std;
int main()
{
?cout << "const_cast演示" << endl;
?const int d = 10;
?int *pd = const_cast(&d);
?(*pd)++;
?cout << "*pd = "<< *pd << endl;
?cout << "d = " << d << endl;
?cin.get();
?return 0;
}
运行

若是把const int d = 10;改为 int d = 10; 则运行结果有变化:*pd = 11; d = 11;
3.reinterpret_cast
这个用于对底层的位模式进行重新解释。
下面这个例子可用来测试系统的大小端。
#include
using namespace std;
int main()
{
?cout << "reinterpret_cast演示系统大小端" << endl;
?int d = 0x12345678;? ? //十六进制数
?char *pd = reinterpret_cast(&d);
?for (int i = 0; i < 4; i++)
?{
? printf("%x\n", *(pd + i));
?}
?cin.get();
?return 0;
}
运行

从运行结果看,我的笔记本是小端的。
4.dynamic_cast
这个用于运行时类型识别。
------------------------------分割线------------------------------
将C语言梳理一下,分布在以下10个章节中: