MSDN dynamic_cast static_cast const_cast reinterpret_cast

dynamic_cast  用于多态类型的转换

static_cast 用于非多态类型的转换

const_cast 用于移除 const, volatile, and__unaligned 属性.

reinterpret_cast 用于指针和类型间的相互转换

// dynamic_cast_1.cpp
// compile with: /c
class B { };
class C : public B { };
class D : public C { };

void f(D* pd) {
   C* pc = dynamic_cast(pd);   // ok: C is a direct base class
                                   // pc points to C subobject of pd 
   B* pb = dynamic_cast(pd);   // ok: B is an indirect base class
                                   // pb points to B subobject of pd
}
// dynamic_cast_2.cpp
// compile with: /c /GR
class A {virtual void f();};
class B {virtual void f();};


void f() {
   A* pa = new A;
   B* pb = new B;
   void* pv = dynamic_cast(pa);
   // pv now points to an object of type A


   pv = dynamic_cast(pb);
   // pv now points to an object of type B
}


// static_cast_Operator.cpp
// compile with: /LD
class B {};

class D : public B {};

void f(B* pb, D* pd) {
   D* pd2 = static_cast(pb);   // not safe, pb may
                                   // point to just B

   B* pb2 = static_cast(pd);   // safe conversion
}


// expre_const_cast_Operator.cpp
// compile with: /EHsc
#include 

using namespace std;
class CCTest {
public:
   void setNumber( int );
   void printNumber() const;
private:
   int number;
};

void CCTest::setNumber( int num ) { number = num; }

void CCTest::printNumber() const {
   cout << "\nBefore: " << number;
   const_cast< CCTest * >( this )->number--;
   cout << "\nAfter: " << number;
}

int main() {
   CCTest X;
   X.setNumber( 8 );
   X.printNumber();
}


// expre_reinterpret_cast_Operator.cpp
// compile with: /EHsc
#include 

// Returns a hash code based on an address
unsigned short Hash( void *p ) {
   unsigned int val = reinterpret_cast( p );
   return ( unsigned short )( val ^ (val >> 16));
}

using namespace std;
int main() {
   int a[20];
   for ( int i = 0; i < 20; i++ )
      cout << Hash( a + i ) << endl;
}



你可能感兴趣的:(C++)