C++ ??dynamic_cast<>???÷?
???????????? ???????[ 2015/2/11 15:14:30 ] ????????C++ ???????
/*???????????μ???????????????? dynamic_cast<> ???÷???*/
/*
?????????????????????????????cast??????????dynamic_cast?????????????????????????????????????????
???????????????
????????dynamic_cast????????null?????????????cast?????????
?????y???dynamic_cast??????????????????????????cast?????????á?
???dynamic_cast???????cast????????????????????麯?????????????μ?????н?CBasic???е?test???????????
virtual??????????????error C2683: dynamic_cast : “CBasic”??????????
????????????
dynamic_cast<> ?????RTTI???????????????“???????????”??????????VC.net 2003???????????
??????????????????????????????????μ???棺
warning C4541: “dynamic_cast”??????? /GR- ????????“CBasic”???
??????2????????????????3?????????????????
???????? Project->Setting?? C/C++ -> C++ Language?????á?
*/
#include <iostream>
using namespace std;
class CBasic
{
public:
virtual int test(){return 0;} // ?????? virtual
};
class CDerived : public CBasic
{
public:
virtual int test(){ return 1;}
};
int main()
{
CBasic cBasic;
CDerived cDerived;
CBasic * pB1 = new CBasic;
CBasic * pB2 = new CDerived;
//dynamic cast failed?? so pD1 is null.
CDerived * pD1 = dynamic_cast<CDerived * > (pB1);
//dynamic cast succeeded?? so pD2 points to CDerived object
CDerived * pD2 = dynamic_cast<CDerived * > (pB2);
//dynamci cast failed?? so throw an exception.
// CDerived & rD1 = dynamic_cast<CDerived &> (*pB1);
//dynamic cast succeeded?? so rD2 references to CDerived object.
CDerived & rD2 = dynamic_cast<CDerived &> (*pB2);
return 0;
}
??????
???·???
??????????????????
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