简而言之,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);//把浮点型转成 字符串型