最新c++中const_cast const_cast用法優(yōu)秀

格式:DOC 上傳日期:2023-05-01 13:50:38
最新c++中const_cast const_cast用法優(yōu)秀
時間:2023-05-01 13:50:38     小編:zdfb

范文為教學中作為模范的文章,也常常用來指寫作的模板。常常用于文秘寫作的參考,也可以作為演講材料編寫前的參考。大家想知道怎么樣才能寫一篇比較優(yōu)質的范文嗎?這里我整理了一些優(yōu)秀的范文,希望對大家有所幫助,下面我們就來了解一下吧。

c++中const_cast const_cast用法篇一

c++中const_cast與reinterpret_cast運算符的用法,經常被用于表達式中的類型轉換,下面是小編分享的運算符的用法,一起來看一下吧。

從類中移除 const、volatile 和 __unaligned 特性。

const_cast <

type-id

> (

expression

)

指向任何對象類型的指針或指向數(shù)據(jù)成員的指針可顯式轉換為完全相同的類型(const、volatile 和 __unaligned 限定符除外)。對于指針和引用,結果將引用原始對象。對于指向數(shù)據(jù)成員的.指針,結果將引用與指向數(shù)據(jù)成員的原始(未強制轉換)的指針相同的成員。根據(jù)引用對象的類型,通過生成的指針、引用或指向數(shù)據(jù)成員的指針的寫入操作可能產生未定義的行為。

您不能使用 const_cast 運算符直接重寫常量變量的常量狀態(tài)。

const_cast 運算符將 null 指針值轉換為目標類型的 null 指針值。

//

// 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 << " before: " << number;

const_cast< cctest * >( this )->number--;

cout << " after: " << number;

}

int main() {

cctest x;

ber( 8 );

umber();

}

在包含 const_cast 的行中,this 指針的數(shù)據(jù)類型為 const cctest *。 const_cast 運算符會將 this 指針的數(shù)據(jù)類型更改為 cctest *,以允許修改成員 number。強制轉換僅對其所在的語句中的其余部分持續(xù)。

reinterpret_cast 運算符

允許將任何指針轉換為任何其他指針類型。也允許將任何整數(shù)類型轉換為任何指針類型以及反向轉換。

reinterpret_cast < type-id > ( expression )

濫用 reinterpret_cast 運算符可能很容易帶來風險。除非所需轉換本身是低級別的,否則應使用其他強制轉換運算符之一。

reinterpret_cast 運算符可用于 char* 到 int* 或 one_class* 到 unrelated_class* 之類的轉換,這本身并不安全。

reinterpret_cast 的結果不能安全地用于除強制轉換回其原始類型以外的任何用途。在最好的情況下,其他用途也是不可移植的。

reinterpret_cast 運算符不能丟掉 const、volatile 或 __unaligned 特性。有關移除這些特性的詳細信息,請參閱 const_cast operator。

reinterpret_cast 運算符將 null 指針值轉換為目標類型的 null 指針值。

reinterpret_cast 的一個實際用途是在哈希函數(shù)中,即,通過讓兩個不同的值幾乎不以相同的索引結尾的方式將值映射到索引。

#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 允許將指針視為整數(shù)類型。結果隨后將按位移位并與自身進行“異或”運算以生成唯一的索引(具有唯一性的概率非常高)。該索引隨后被標準 c 樣式強制轉換截斷為函數(shù)的返回類型。

s("content_relate");

【c++中const-cast與reinterpret-cast運算符的用法】相關文章:

c++ 中--declspec 的用法詳解

10-06

c語言位運算符的用法

11-02

c語言位運算符的用法指導

10-06

c++中時間與時間戳的轉換

10-04

java中運算符的使用

09-29

c++中內聯(lián)函數(shù)的應用

10-25

php中抽象類與抽象方法的用法

09-29

c++中輸入多組數(shù)據(jù)的方法

10-06

c++ 中引用和指針的關系

09-30

【本文地址:http://www.aiweibaby.com/zuowen/2780139.html】

全文閱讀已結束,如果需要下載本文請點擊

下載此文檔