C++-類型轉換(static_cast, const_cast, reinterpret_cast)


static_cast 表示靜態變量的類型轉換, 如int->char, 不合適的類型轉換將會發生錯誤

/*
static_cast 類型轉換 
*/ 
#include <iostream>

using namespace std; 

int main() {
    int* pi = NULL; 
    //char c = int(pi); //C++類型轉換 
    //char c = (int)pi; //C類型轉換 
    void* pc = pi; 
    pi = static_cast<int *>(pc); 
    char c = static_cast<int>(pi); //會出現報錯,因為int* 無法轉換為int類型  

}

const_cast 表示const類型和非const類型的相互轉換

/* 
const_cast
*/
#include <iostream>

using namespace std; 

int main() {
    //volatile表示易變的,可以變化的 
    const volatile int ci = 100; //表示數字是易變 
    int* pi = const_cast<int *>(&ci); //進行地址的賦值操作
    *pi = 200; //對地址進行賦值 
    cout << *pi << endl; 
    cout << ci << endl; 
    cout << (void *)&ci << endl; 
    cout << pi << endl; 
}

reinterpret_cast 表示進行隱式轉換

/*
進行隱式轉換
*/ 
#include <iostream>

using namespace std; 

int main(void) {
    //\000 = "\0" --> 0 
    char buf[] = "0001\00012345678\000123456"; 
    struct Http {
        char type[5]; 
        char id[9]; 
        char passward[7]; 
    };
    Http *p_http = reinterpret_cast<Http*>(buf); 
    cout << p_http->type << endl; 
    cout << p_http->id << endl; 
    cout << p_http->passward << endl; 
    return 0; 
}

 


免責聲明!

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



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