c++中的類型轉換,static_cast,reinterpret_cast,boost::lexical_cast

 簡而言之,static_cast<> 將嘗試轉換,舉例來說,如float-到-integer,而reinterpret_cast<>簡單改變編譯器的意圖重新考慮那個對象作爲另一類型。

 

float f=123.4;
int i=(int)f;//正確
int j=static_cast<int>(f);//正確
int j=boost::lexical_cast<int>(f);  //錯誤
int j=boost::lexical_cast<int>(f*10);//正確 

 

char ch[4]="123";
int bdl=static_cast<int>(ch[2]);//正確 51(3的ASCII碼):轉換成相應的ASCII碼
int bjl=boost::lexical_cast<int>(ch[2]);//正確 3
int bd1=static_cast<int>(ch);//編譯錯誤,不能這麼轉換
int bj1=boost::lexical_cast<int>(ch);//正確 123

===================================

static_cast:

alra::TCPMSG* pTCPMSG = (alra::TCPMSG*)wParam;

浮點型轉成整形
ptTopLeft.y = static_cast<int>(rct.Height() * (1.0/5));

把一字節轉成無符號BYTE
ASSERT(0x0f == static_cast<BYTE>(pData[2]));

static_cast<unsigned int>(static_cast<unsigned char>(iocem.szData[i]))

從參數中取出整形:
int nCommandID = static_cast<int>(wParam);

把整形轉成參數類型:
static_cast<LPARAM>(nCommandID)
static_cast<UINT>(nCommandID)

static_cast<WPARAM>(MAKEWORD(nMorSFibler ,nCommRoute )),static_cast<LPARAM>(MAKEWPARAM(nRorSPort,MAKEWORD(nNewStaus ,nOldStaus ))

 

取得類指針,然後轉成指定的類:
CPageDeviceBoxIOPM* pParent = static_cast<CPageDeviceBoxIOPM*>(GetParent());
return static_cast<CDocDevice*>(static_cast<CFormDevice*>(pParent)->GetDocument());

傳遞指針類型:
AfxBeginThread(AlraCommit::SendThread , static_cast<LPVOID>(pParam));
alra::PSENDINGTHREADPARAM pParam = static_cast<alra::PSENDINGTHREADPARAM>(lParam);


----------------------------------------------------------------------------------

reinterpret_cast:

unsigned char* p = reinterpret_cast<unsigned char*>(pData + 5);

傳遞消息指針參數:
PostMessage(alra::UM_SEND_A_PACKAGE, reinterpret_cast<WPARAM>(pCardParam), 0);
alra::PSENDINGTHREADPARAM pCardParam = reinterpret_cast<alra::PSENDINGTHREADPARAM>(wParam);

引用轉換爲具體的類型:
alra::IOCEM& iocem = reinterpret_cast<alra::IOCEM&>(rPackage);
alra::IOPM& iopm = reinterpret_cast<alra::IOPM&>(rPackage);

ret = ::SQLPrepare(hstmt, reinterpret_cast<UCHAR*>(strSQL.GetBuffer(0)), SQL_NTS);


GetParent()->PostMessage(alra::UM_DEVICE_CARD_SELECTION_CHANGE,
      static_cast<WPARAM>(GetDlgCtrlID()), //傳遞整形
      reinterpret_cast<LPARAM>(pCard));    //傳遞指針型


------------------------------------------------------------------------------

boost::lexical_cast:

把字符型轉爲int型,然後轉成起BYTE型,例如 vs[3]='2',先轉成int 2,然後轉成 BYTE,爲OX02 0000 0010
MAKEWORD(static_cast<BYTE>(boost::lexical_cast<int>(vs[3])), static_cast<BYTE>(boost::lexical_cast<int>(vs[2])))
把字符串轉成double:
boost::lexical_cast<double>(strValue);
把EDIT控件關聯的cstring變量轉成double型:
boost::lexical_cast<double>(m_strMRLimit2.GetBuffer());

當下面兩個裏面×10後沒小數點時,二者效果一樣,有小數時,lexical_cast<int>會出錯
iopm.nSwitchLimit =            static_cast<int>(boost::lexical_cast<double>(m_strSRSwitchThreshold.GetBuffer()) * 10.0);
iocem.nChanged    =    boost::lexical_cast<int>(boost::lexical_cast<float>(this->m_strChanged) * 10);

std::string s = lexical_cast<std::string>(123456.7);//把浮點型轉成 字符串型

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章