C++?????????????
???????????? ???????[ 2014/11/24 11:47:44 ] ????????C++ ?????? ???????
????1.static_cast
?????÷???static_cast < type-id > ( expression )?????????expression????type-id????????????????????????????????????
?????????????ν??л?????????????????????????????????????
?????????????????????????????????????????????????????
??????????????????????????????????????????????????????ж???????飬?????????????
?????????????????????????????????int?????char????int?????enum???????????????????????????????
????????????????????????????
????????κ??????????????void?????
???????static_cast?????????expression??const??volatile??????__unaligned?????
????class CBase {};
????class CDerived: public CBase {};
????CBase * a = new CBase;
????CDerived * b = static_cast<CDerived*>(a);
?????????????????????????????????b???????????????????????????????????????????????
????int i;
????float f = 166.71;
????i = static_cast<int>(f);
????????????i????166??
????2.dynamic_cast
????dynamic_cast < type-id > ( expression )
?????????????expression?????type-id????????type-id??????????????????????void*?? ???type-id???????????????expression????????????????
????type-id?????????????expression?????????????á?
????dynamic_cast??????????μ???????????????????????????????????????????????μ?????????????????????static_cast??Ч??????????
????class CBase { };
????class CDerived: public CBase { };
????CBase b; CBase* pb;
????CDerived d; CDerived* pd;
????pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
????pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived
???????????????????????????????????????????????????????????????????dynamic_cast?????????????????????????????Ч???????????????????:
// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;
class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;
pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
?????????????
????Null pointer on second type-cast
????dynamic_cast???????????????(RTTI)???????????
??????
???·???
??????????????????
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