C++類型轉換

C++強制轉換

1非強制轉換 charintdoublefloat

Static_cast<int>( )

 char a = 1;

 int b = static_cast<int>(a);=1

2使用void *的強制類型轉換

struct callback_param

{

    void *vp;

};

 int a = 1;

struct callback_param cp;

cp.vp = &a;      //編譯器允許從任意類型指針向void*轉換

 pr=p;              //error:不能將空類型指針賦給其他指針

 int *ip = static_cast<int *>(cp.vp);

類型轉換的意義是調用正確的重載函數

 char buffer[5];

 cout<<(void*)buffer;

輸出buffer字符串的地址

errorstray'\243'in program{},()的錯誤

int i;

float f = 166.7f;

i = static_cast<int>(f);

此時結果,i的值爲166

3常量轉換(const_cast

const轉換爲非const,從volatile轉換爲非volatile。取得const對象的地址,會生成一個指向const的指針,volatile同。

 一、常量指針被轉化成非常量指針,並且仍然指向原來的對象;

 二、常量引用被轉換成非常量引用,並且仍然指向原來的對象;

 三、常量對象被轉換成非常量對象。

const int i = 0;

int *ip = const_cast<int *>(&i);

 

volatile int a = 0;

int *ap = const_cast<int *>(&a);

3、重解釋轉換(reinterpret_cast

最不安全的一種轉換機制,將對象轉變爲完全不同類型的對象,這是低級的位操作。

 

struct msg_hdr

{

    int msg_type;

    int msg_len;

    char msg_data[0];

};

 

struct msg_data

{

    int data1;

    int data2;

};

 

struct msg_hdr *p = reinterpret_cast<struct msg_hdr *>(recvbuf);

struct msg_data *pdata = reinterpret_cast<struct msg_data *>(p->msg_data);

4

 

發佈了18 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章