??C++?????????????
???????????? ???????[ 2012/9/27 10:15:06 ] ????????
????C++???????????C??????C?????????????÷?????????????????????????????????????????????????????????C++?????????????????????????????????????????????????????????????????????????????????????????ж???????
??????????????????C++??????????????????????????????幦????÷???
????1??const_cast
????2??static_cast
????3??reinterpret_cast
????4??dynamic_cast
???????????????????÷???????????????cast-name<Type>??expression????Type???????expression??????????
???????濴???????????????????ó????
????1??const_cast
??????????壬const_cast?????????const???????????磺
char* string_copy(char* s) { return s; } int main() { const char* pc_str; char* pc = string_copy(const_cast<char*>(pc_str));//????????pc_str???????? return 0; } |
?????????????????????????????
??????????const_cast??????????????const????????????????????????const_cast??
????2??static_cast
???????????????????????????е??κ????????????????static_cast??ɡ?
????????static_cast??????????void*???????????????????????????????磺
double d = 12; void* p = &d; double* pd = static_cast<double*>(p); cout << *pd << endl; |
???????????12?????????????????????????????
????3??reinterpret_cast
????????????????????????????????????Σ????????????????????????????????
????????????????????????????????磺
int* ip; char* pc = reinterpret_cast<char*>(ip); string str(pc); |
?????????????????????????????????????????????????????????reinterpret_cast????á?
????4??dynamic_cast
????dynamic_cast?????????????????????????????????????????????????????????á?
????dynamic_cast?????????????????????漰??????????顣?????????????????????????????????????????dynamic_cast???????????????????????dynamic_cast?????0????????????????????????????bad_cast????
??????????????????????????????м??
????????????
if(Derived *derviedPtr = dynamic_cast<Derived*>(basePtr){ // use the Derived object to which derivedPtr points } else{ // basePtr oiubsts at a Base object // use the Base object to which basePtr points } |
?????????????
void f(const Base& b) { try{ const Derived& d = dynamic_cast<const Derived&>(b); // use the Derived object to which b referred } catch (bad_cast){ // handle the fact that the cast failed } } |
??????????????????????????
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11