詳解C++中const_cast與reinterpret_cast運算符的用法。本站提示廣大學習愛好者:(詳解C++中const_cast與reinterpret_cast運算符的用法)文章只能為提供參考,不一定能成為您想要的結果。以下是詳解C++中const_cast與reinterpret_cast運算符的用法正文
const_cast 運算符
從類中移除 const、volatile 和 __unaligned 特征。
語法
const_cast < type-id > ( expression )
備注
指向任何對象類型的指針或指向數據成員的指針可顯式轉換為完整雷同的類型(const、volatile 和 __unaligned 限制符除外)。關於指針和援用,成果將援用原始對象。關於指向數據成員的指針,成果將援用與指向數據成員的原始(未強迫轉換)的指針雷同的成員。依據援用對象的類型,經由過程生成的指針、援用或指向數據成員的指針的寫入操作能夠發生不決義的行動。
您不克不及應用 const_cast 運算符直接重寫常質變量的常量狀況。
const_cast 運算符將 null 指針值轉換為目的類型的 null 指針值。
// expre_const_cast_Operator.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class CCTest {
public:
void setNumber( int );
void printNumber() const;
private:
int number;
};
void CCTest::setNumber( int num ) { number = num; }
void CCTest::printNumber() const {
cout << "\nBefore: " << number;
const_cast< CCTest * >( this )->number--;
cout << "\nAfter: " << number;
}
int main() {
CCTest X;
X.setNumber( 8 );
X.printNumber();
}
在包括 const_cast 的行中,this 指針的數據類型為 const CCTest *。 const_cast 運算符會將 this 指針的數據類型更改成 CCTest *,以許可修正成員 number。強迫轉換僅對其地點的語句中的其他部門連續。
reinterpret_cast 運算符
許可將任何指針轉換為任何其他指針類型。也許可將任何整數類型轉換為任何指針類型和反向轉換。
語法
reinterpret_cast < type-id > ( expression )
備注
#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 許可將指針視為整數類型。成果隨後將按位移位並與本身停止“異或”運算以生成獨一的索引(具有獨一性的幾率異常高)。該索引隨後被尺度 C 款式強迫轉換截斷為函數的前往類型。