共用方式為


reinterpret_cast 運算子

可讓任何指標,以指定須轉換成任何指標型別。 也可讓任何整數類資料型別,以指定須轉換成任何指標型別,反之亦然。

reinterpret_cast < type-id > ( expression )

備註

誤用reinterpret_cast運算子可以很輕易就不安全。 除非您想要的轉換為原本就低層級,否則您應該使用其他的型別轉換運算子的其中一個。

reinterpret_cast運算子可以用來進行轉換例如char*到int*,或One_class*到Unrelated_class*,這是原本就不安全。

將reinterpret_cast無法安全地用於以外的其他轉換回其原始的型別。 其他的用途是,最多只能不可移植。

reinterpret_cast運算子無法轉換開 const, volatile,或 __unaligned 屬性。 請參閱 const_cast 運算子如需移除這些屬性的詳細資訊。

reinterpret_cast運算子將 null 指標值轉換成目的型別時發現 null 指標值。

實際使用一reinterpret_cast在雜湊函式,何種方式,使得該兩個不同的索引值的對應值很少結束往上擁有相同的索引。

// expre_reinterpret_cast_Operator.cpp
// compile with: /EHsc
#include <iostream>

// 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;
}

reinterpret_cast可讓被視為整數型別指標。 結果再加上位元移位,並與它本身的進行 xor 處理,以產生唯一的索引 (唯一較高程度的可能性)。 索引是再被截斷標準 c-style 轉換成函式的傳回型別。

請參閱

參考

轉型運算子

C + + 關鍵字