1、reinterpret_cast
Allows any pointer to be converted into any other pointer type. Also allows any integral type to be converted into any pointer type and vice versa.
样例
int _tmain(int argc, _TCHAR* argv[])
{
CCTest objTest;
CCBase *p = (CCBase*)reinterpret_cast<void*>(&objTest);
p->SetNumber1(1); //CCBase::SetNumber1
CCTest *p2 = (CCTest*)reinterpret_cast<void*>(&objTest);
p2->SetNumber1(1); //CCTest::SetNumber1
unsigned int val = reinterpret_cast<unsigned int>( &objTest ); //objTest的地址
return 0;
}
2、const_cast
Removes the const, volatile, and __unaligned attribute(s) from a class.
样例:
int _tmain(int argc, _TCHAR* argv[])
{
int a = 12;
const int& a1= a;
const_cast<int&>(a1) =21; // a:21,移除const常量声明
a1 =12; //Error:“a1”: 不能给常量赋值
return 0;
}
样例
class CCTest {
public:
void SetNumber1(int val) const
{
const_cast<CCTest*>(this)->number = val; //ok
}
void SetNumber2(int val) const
{
number = val; //error C3490: 由于正在通过常量对象访问“number”,因此无法对其进行修改
}
private:
int number;
};
3、dynamic_cast
可以进行两个方向转换,downcast,upcast, 也就是派生类指针转换成基类指针,也可以基类指针转换成派生类指针。如果基类指针指向的对象地址是派生类对象,那么转换指针非空,否者为NULL.
CShape *pShape1 = new CRectangle();
try
{
CRectangle* p = dynamic_cast<CRectangle*>(pShape1);
}
catch (std::bad_cast&)
{
}