強制型変換

2450 ワード

C++        :static_cast、reinterpret_cast、const_cast、dynamic_cast.

static_cast:            (    ),             ,                。static_cast             。
 :
       int i = 2;
       double d = static_cast<double>(i); //  ,            
       int *p = &i;
       double d = static_cast<double>(p);//  ,    ,     



reinterpret_cast:                     .
 :
typedef void(*FUNC)();
int DoSomthing(int i)
{
       cout << "DoSomthing():" << i << endl;
       return 0;
}
void test()
{
       FUNC pf = reinterpret_cast<FUNC>(DoSomthing);
       pf();
}
reinterpret_cast:       FUNC        DoSomething  ,               。    ,reinterpret_cast   BUG。


const_cast:             const  ,    。
 :
void test()
{
       const int i = 10;
       int* b =const_cast<int *>(&i);
       *b = 20;
       cout << i << endl;      //   10,        ,          
       cout << *b << endl;     //   20,b      i,        
}

void test()
{
       volatile const int i = 10;   
       int* b =const_cast<int *>(&i);
       *b = 20;
       cout << i << endl;      //   20,  volatile       
       cout << *b << endl;    
}

dynamic_cast:                            。
1、dynamic_cast           
2、              ,    0,            ,     。
 :
void test()
{
       A a;
       B b;
       A *pa = &a;  //  ,          
       pa = &b;     //  ,          
       //B *pb = &a;  //c  ,          
       B *pb = &b;      //  ,          
}

void fun(A *pa)
{
       B *pb = dynamic_cast<B *>(pa);        //  pa      ,   0,        ,    
       cout << "pb1:" << pb<< endl;
}
void test()
{
       A a;
       B b;
       fun(&a);           
       cout << &a << endl;
       fun(&b);
       cout << &b<< endl;
}

explicit:                 
 :
class A
{
public:
       A(int a)
              :_a(0){}
       A(const A& a)
       {
       }
private:
       int _a;
};
void test()
{
       A a1(1);  //     
       //1      A tmp(1),A a2(tmp)
       A a2 = 1;       //  
}


class A
{
public:
       explicit A(int a)
              :_a(0){}
       A(const A& a)
       {
       }
private:
       int _a;
};
void test()
{
       A a1(1);  //     
       //1      A tmp(1),A a2(tmp)
       A a2 = 1;    //  
}
             ,           explicit.