׼C++ǿת Builder.com.cn ʱ:2007-09-26ߣghost Դ:CSDN
Ĺؼʣ ghost c++ ǿ ת 
1static_casta
ַaתTTaָ롢áͻö͡
ʽstatic_cast< T > ( a ) aֵתΪģָTʱתУͼȷתİȫԡ
2dynamic_casta
νṹеTһָ롢û͵ָ롣aǾһָõıʽ
ʽdynamic_cast< T >( a ) aֵתΪΪTĶָ롣Taĳͣòһָ롣
3const_casta
ȥеĳconstȶıַTaͬ͡
ʽconst_cast< T >( a )ڴһȥЩԣconst, volatile,  __unaligned
4reinterpret_casta
κָ붼ת͵ָ룬Tһָ롢áָָָ͡һԱָ롣
ʽreinterpret_cast< T >( a )ܹchar*  int*One_class*  Unrelated_class*ת˿ǲȫġ






++  cast-name(expression) ǿת C ķʽʾ cast-name(expression) ʹתпԣһԱرÿʽǿתǱڵķռ
ǿתķࣺ
dynamic_cast

ͶûָתΪͬһ̳в͵ûָ롣£



// ָǿת
if (Derived* pDerived = dynamic_cast<Derived*>(pBase))
{
  // successd
}else{
  // failure
}

// õǿת
try{
  const Derived& derived = dynamic_cast<Derived&>(base);
}catch(bad_cast){
  // handle the fact that the cast failed
}

ע⣺ dynamic_cast ֻΪһ麯෵ض̬Ϣͣؾ̬ʱ͵Ϣ

ע ӻΪõķͨ麯ֻڲʹ麯ʹ RTTIΪֻƱʹ麯׳Ա֪ӦýǿתΪͣҼתǷɹ

const_cast

תʽ const ʡ磺 



const char* pcStr;
char* pStr = const_cast<char*>(pcStr);

 

static_cast

ʽִеκת static_cast ʽɣ 




double d = 100.0;
char c = static_cast<char>(d);

void* p;
double* pD = static_cast<double*>(p); 
 

reinterpret_cast

ΪλģʽṩϵͲε½ͣ



int* pI;
char* pC = reinterpret_cast<char*>(pI); 
³http://www.diybl.com/course/3_program/c++/cppjs/200843/108261.html













 1static_cast   Ǿ̬תֻͼݵת(ɿխ),   RUNTIME   Զָ̬иЧdowncastingǵתָʵָʱûṩ   
     
    static_cast(expression)expressionתػڱʽиtype_id͡ûͼ鱻ִȷתİȫԡstatic_castɱתһָ뵽һָĲ,תǰȫ,Զ,dynamic_castǰȫġ 

    ע⣺static_cast<>()תֻǷصǰǿתֵҲ˵ʹøòǿתʱ򣬲ıתԴֵֻʱԴֵתֵҪһתԺֵ 

     



 class B { ... };  
class D : public B { ... };  
void f(B* pb, D* pd)  
{  
    D* pd2 = static_cast<D*>(pb);        // ȫ, pbֻBָ  
    B* pb2 = static_cast<B*>(pd);        // ȫ  
    ...  
}   



    2 dynamic_cast   Ƕ̬תҪbasederivedת˵Լtype   information,type   informationתвʧ   

     



 class A { ... };  
class B { ... };  
void f()  
{  
   A* pa = new A;  
   B* pb = new B;  
   void* pv = dynamic_cast<void*>(pa);  
   // pv ָһΪAĶ  
   ...  
   pv = dynamic_cast<void*>(pb);  
   // pv ָһΪBĶ  
}   



    3reinterpret_castκָ뱻תκָ, κתָ,ҷ֮Ȼreinterpret_cast׵²ȫ,תǹеĵ͵ȼ,Ӧʹת֮һ 

     

 class A { ... };  
class B { ... };  
void f()  [Page]
{  
   A* pa = new A;  
   void* pv = reinterpret_cast<B*>(pa);  
   // pv ָһΪBĶǲȫ  
   ...  
}  


    4const_castɱڴһгȥconstvolatile_   _unalignedκζ͵ָһݳԱָɱʽתȫͬ,constvolatile__unaligned޶⡣ָ,ָԴ,ݳԱָݳԱԴָһָͬһԱö,ָͨ롢ûݳԱָдδĶ  
  
    


 class A { ... };  
void f()  
{  
  const A *pa = new A;//const  
  A *pb;//const  
//pb = pa; // ｫܽconstָ븳ֵconst  
  pb = const_cast<A*>(pa); // OK  
...  
}  

