C++拾遗--name_cast 显式类型转换


前言

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\n", *(pd + i));
 }
 cin.get();
 return 0;
}

运行

从运行结果看,我的笔记本是小端的。

4.dynamic_cast

这个用于运行时类型识别。

------------------------------分割线------------------------------

C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码

读C++ Primer 之构造函数陷阱

读C++ Primer 之智能指针

读C++ Primer 之句柄类

将C语言梳理一下,分布在以下10个章节中:

  1. Linux-C成长之路(一):Linux下C编程概要
  2. Linux-C成长之路(二):基本数据类型
  3. Linux-C成长之路(三):基本IO函数操作
  4. Linux-C成长之路(四):运算符
  5. Linux-C成长之路(五):控制流
  6. Linux-C成长之路(六):函数要义
  7. Linux-C成长之路(七):数组与指针
  8. Linux-C成长之路(八):存储类,动态内存
  9. Linux-C成长之路(九):复合数据类型
  10. Linux-C成长之路(十):其他高级议题

本文永久更新链接地址:

相关内容