C 的四種型別轉換

2021-09-27 02:06:57 字數 1176 閱讀 2984

c++強制型別轉換

static_cast、reinterpret_cast、const_cast、dynamic_cast

1. static_cast

static_cast用於非多型型別的轉換(靜態轉換),編譯器隱式執行的任何型別轉換都可用static_cast,但它不能用於兩個不相關的型別進行轉換

double d =

12.34

;int a =

static_cast

<

int>

(d);

2. reinterpret_cast

reinterpret_cast操作符通常為運算元的位模式提供較低層次的重新解釋,用於將一種型別轉換為另一種不同的型別。

typedef

void

(* func)()

;int dosomething (

int i)

void test (

)

3. const_cast

const_cast最常用的用途就是刪除變數的const屬性,方便賦值

void test (

)

4. dynamic_cast

classa}

;classb:

public a

;void

fun(a* pa)

intmain()

explicit

explicit關鍵字阻止經過轉換建構函式進行的隱式轉換的發生

classaa

(const a& a)

private

:int _a ;};

int main (

)

為什麼c++需要四種型別轉換

rtti

rtti:run-time type identification的簡稱,即:執行時型別識別。

c++通過以下方式來支援rtti:

typeid運算子

dynamic_cast運算子

c 四種型別轉換

c風格的強制型別轉換 type cast 很簡單,不管什麼型別的轉換統統是 type b type a。c 風格的型別轉換提供了4種型別轉換操作符來應對不同場合的應用。const cast,字面上理解就是去const屬性。static cast,命名上理解是靜態型別轉換。如int轉換成char。dy...

C 四種型別轉換

include include includeusing namespace std static cast 用法 static cast type id expression 該運算子把expression轉換為type id型別,但沒有執行時型別檢查來保證轉換的安全性。它主要有如下幾種用法 用於...

C 四種型別轉換

1 static cast 1.上行轉換,把派生類的指標或引用轉換成基類,此時是安全的 2.下行轉換,把基類的指標或者引用轉換成派生類,因為沒有動態監測,所以是不安全的 3.顯示型別轉換,如int轉float等 4.任意型別空指標轉任意型別空指標 5.任意型別表示式轉為void型別 如下 int a...