前言C++中提供了四种显式的类型转换方法:static_cast,const_cast,reinterpret_cast,dynamic_cast.下面分别看下它们的使用场景。显式类型转换1.staitc_cast这是最常用的,一般都能使用,除了不能转换掉底层const属性。#include <iostream>
using namespace std;int main()
{
cout << "static_cast转换演示" << endl;
int i = 12, j = 5;
//对普通类型进行转换
double res = static_cast<double>(i) / j;
cout << "res = "<< res << endl;
float f = 2.3;
void *pf = &f;
//把void*转换为指定类型的指针
float *ff = static_cast<float*>(pf);
cout << "*ff = " << *ff << endl;
/*
int cd = 11;
const int *pcd = &cd;
int *pd = static_cast<int*>(pcd); //error static_const 不能转换掉底层const
*/
cin.get();
return 0;
}运行对于变量的const属性分为两种:顶层的、底层的。对于非指针变量而言两者的意思一样。对于指针类型则不同。如int *const p; p的指向不可改变,这是顶层的;const int *p; p指向的内容不可改变,这是底层的。2.const_cast用法单一,只用于指针类型,且用于把指针类型的底层const属性转换掉。#include <iostream>
using namespace std;int main()
{
cout << "const_cast演示" << endl;
const int d = 10;
int *pd = const_cast<int*>(&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 <iostream>
using namespace std;int main()
{
cout << "reinterpret_cast演示系统大小端" << endl;
int d = 0x12345678; //十六进制数
char *pd = reinterpret_cast<char*>(&d);
for (int i = 0; i < 4; i++)
{
printf("%x
", *(pd + i));
}
cin.get();
return 0;
}运行从运行结果看,我的笔记本是小端的。4.dynamic_cast这个用于运行时类型识别。------------------------------分割线------------------------------
C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htm读C++ Primer 之构造函数陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm读C++ Primer 之智能指针 http://www.linuxidc.com/Linux/2011-08/40177.htm读C++ Primer 之句柄类 http://www.linuxidc.com/Linux/2011-08/40175.htm
将C语言梳理一下,分布在以下10个章节中:- Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
- Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
- Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
- Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
- Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
- Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
- Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
- Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
- Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
- Linux-C成长之路(十):其他高级议题
本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-02/113670.htm