class CDerivedClass : public CMyBase {...};class CMyOtherStuff {...} ;
CMyBase *pSomething; // filled somewhere
现在,这两个是以相同的方式编译的:
CDerivedClass *pMyObject;pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked
pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>// Safe; as long as we checked// but harder to read
但是,让我们看看这个几乎相同的代码:
CMyOtherStuff *pOther;pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert
pOther = (CMyOtherStuff*)(pSomething); // No compiler error.// Same as reinterpret_cast<>// and it's wrong!!!
pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);// No compiler error.// but the presence of a reinterpret_cast<> is// like a Siren with Red Flashing Lights in your code.// The mere typing of it should cause you to feel VERY uncomfortable.
int i;double d = (double)i; //C-style castdouble d2 = static_cast<double>( i ); //C++ cast
这两种方法都将整数值转换为双精度。然而,当使用指针时,事情变得更加复杂。一些例子:
class A {};class B : public A {};
A* a = new B;B* b = (B*)a; //(1) what is this supposed to do?
char* c = (char*)new int( 5 ); //(2) that weird?char* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error