reinterpret_cast 運算子
可將所有指標轉換成任何其他指標類型。 也可將任何整數類資料類型轉換成任何指標類型 (反之亦然)。
語法
reinterpret_cast < type-id > ( expression )
備註
reinterpret_cast
誤用運算子很容易不安全。 除非所需的轉換本質屬於低階轉換,否則您應使用其他任一轉型運算子。
reinterpret_cast
運算子可用來轉換 ,例如 char*
,或 One_class*
轉換成 int*
Unrelated_class*
原本不安全的 。
的結果 reinterpret_cast
無法安全地用於轉換成其原始類型以外的任何專案。 其他用途的最佳情況是不可攜。
運算子 reinterpret_cast
無法轉換 const
、 volatile
或 __unaligned
屬性。 如需移除這些屬性的相關信息,請參閱 const_cast 運算符 。
運算子 reinterpret_cast
會將 Null 指標值轉換為目的地類型的 Null 指標值。
其中一個實際用法 reinterpret_cast
是在哈希函式中,其會將值對應至索引,如此一來,兩個相異值很少會得到相同的索引。
#include <iostream>
using namespace std;
// Returns a hash code based on an address
unsigned short Hash( void *p ) {
unsigned int val = reinterpret_cast<unsigned int>( p );
return ( unsigned short )( val ^ (val >> 16));
}
using namespace std;
int main() {
int a[20];
for ( int i = 0; i < 20; i++ )
cout << Hash( a + i ) << endl;
}
Output:
64641
64645
64889
64893
64881
64885
64873
64877
64865
64869
64857
64861
64849
64853
64841
64845
64833
64837
64825
64829
reinterpret_cast
允許將指標視為整數型別。 結果隨即位元移位並與其本身 XOR,以產生唯一的索引 (高可攜性獨有)。 之後,標準 C-Style 轉換會將該索引截斷為函式的傳回型別。