三、static_cast
static_cast的用途有3个:
1. 基本数据类型之间的相互转化;
2. 派生类指针或引用 和 基类指针或引用的相互转化。(dynamic_cast在把基类指针转化成派生类指针时,会编译错误;而static_cast不会提示编译错误,但是这种转化是不安全的。)
3. 各种指针类型 转换成 void *类型. (如果使用static_cast把void*类型转化为其它指针类型,编译器不会报错,但是转化行为不安全。)
1 class CBase {public: int bb;}; 2 class CDerived: public CBase {public:int dd; }; 3 4 int main(){ 5 CBase b; CBase* pb; CBase* pb2; 6 b.bb = 50; 7 CDerived d; CDerived* pd; 8 d.bb =100;d.dd=200; 9 void * p = NULL; 10 pb = static_cast<CBase*>(&d); // ok: derived-to-base 11 pd = static_cast<CDerived*>(&b); // base* ->derived *, not safe 需要程序员保证指向完整的派生类对象 12 13 p = static_cast<void*>(&d); // other * -> void *, OK 14 pb = static_cast<CBase*>(p); // void * -> other *, not safe. 15 pb2 = static_cast<CDerived*>(p);// void * -> other *, not safe. 16 17 int dwA=10, *pB = NULL; 18 short int *pA=NULL, wB =20; 19 // pA = static_cast<short int *> (&dwA); // int * -> short * ,compile error. 20 // pB = static_cast<int *> (&wB); // short * -> int * ,compile error. 21 22 p = static_cast<void *> (&wB);// other * -> void *, OK. 23 pB = static_cast<int *> (p);// void * -> other *, not safe. 24 uint64_t * pB2 = static_cast<uint64_t *> (p);// void * -> other *, not safe. 25 26 wB = static_cast<short int> (dwA);// conversion between fundmental types, OK. 27 dwA= static_cast<int>( wB);// conversion between fundmental types, OK. 28 cout<<endl; 29 return 0; 30 }