C++中的強制類型轉換


在C語言中,強制類型轉換的方式為(Type)Expression,另外還有一種現在已經不用的舊式寫法Type(Expression),這兩種方式是等價的。

但是,C語言的強制類型轉換方式存在一些問題:

  • 過於粗暴,可以在任意類型之間進行轉換,編譯器很難判斷其正確性
  • 難於定位,在源代碼中無法快速定位所有使用強制類型轉換的語句

然而,強制類型轉換在實際工程中幾乎是不可避免的,為此C++將強制類型轉換分為4種不同的類型,以提供更加安全可靠的轉換。

強制類型轉換 說 明
static_cast 用於基本類型之間、有繼承關系的類對象之間、類指針之間的轉換
不能用於基本類型指針之間的轉換
const_cast 用於去除變量的只讀屬性
強制轉換的目標類型必須是指針或引用
reinterpret_cast 用於指針類型之間、整數和指針類型之間的轉換
dynamic_cast 用於有繼承關系的類指針之間、有交叉關系的類指針之間的轉換
具有類型檢查的功能
需要虛函數的支持

C++提供的4種強制類型轉換以關鍵字的方式出現,使用語法為:xxx_cast<Target Type>(Expression)

#include <stdio.h>

void static_cast_demo()
{
    int i = 0x12345;
    char c = 'c';
    int *pi = &i;
    char *pc = &c;

    c = static_cast<char>(i);
    pc = static_cast<char *>(pi); // Error,static_cast不能用於基本類型指針間的轉換
}

void const_cast_demo()
{
    const int &j = 1;
    int &k = const_cast<int &>(j);

    const int x = 2;
    int &y = const_cast<int &>(x);

    int z = const_cast<int>(x);  // Error,const_cast的目標類型必須是指針或引用
}

void reinterpret_cast_demo()
{
    int i = 0;
    char c = 'c';
    int *pi = &i;
    char *pc = &c;

    pc = reinterpret_cast<char *>(pi);
    pi = reinterpret_cast<int *>(pc);
    pi = reinterpret_cast<int *>(i);
    c = reinterpret_cast<char>(i); // Error,reinterpret_cast不能用於基本類型間的轉換
}

void dynamic_cast_demo()
{
    int i = 0;
    int *pi = &i;
    char *pc = dynamic_cast<char *>(pi); // Error,dynamic_cast只能用於有繼承關系或交叉關系的類指針間的轉換,且類中必須有虛函數
}

int main()
{
    static_cast_demo();
    const_cast_demo();
    reinterpret_cast_demo();
    dynamic_cast_demo();

    return 0;
}

可以看出,使用新的強制類型轉換

  • 在編譯時能夠幫助檢查潛在的問題
  • 搜索4個關鍵字,可以非常方便在代碼中定位


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM