歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++拾遺--name_cast 顯式類型轉換

C++拾遺--name_cast 顯式類型轉換

日期:2017/3/1 9:32:56   编辑:Linux編程

前言

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+源代碼 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個章節中:

  1. Linux-C成長之路(一):Linux下C編程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成長之路(二):基本數據類型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成長之路(三):基本IO函數操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成長之路(四):運算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成長之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成長之路(六):函數要義 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成長之路(七):數組與指針 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成長之路(八):存儲類,動態內存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成長之路(九):復合數據類型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成長之路(十):其他高級議題

Copyright © Linux教程網 All Rights Reserved