close

 

C++ type casting :

 

  1. static_cast<TYPE>( OBJ )

  2. dynamic_cast<TYPE>( OBJ )

  3. reinterpret_cast<TYPE>( OBJ )

  4. const_cast<TYPE>( OBJ )

 

Example :

 

 #1 ) static_cast< T >( ... )

 

Like : int i = (int) pi;

 
#include <iostream>
 
using namespace std;
 
int main() {
    
    double pi = 3.14;
    int i = static_cast<int>( pi );
        
    return 0;
}
 

 

 #2 ) dynamic_cast< T >( ... )

 

Safe downcasting. ( Run time )

** if( CASTING_FAIL ) return 0;

 
#include <iostream>
 
using namespace std;
 
class A {
public:
    virtual void funcA(void) {;}
};
 
class B : public A {
public:
    void funcB(void) {;}
};
 
int main() {
    
    A *a = new A();
    B *b = dynamic_cast<B*>( a );
    
    return 0;
}
 

 

 #3 ) reinterpret_cast< T >( ... )

 

Pointer to pointer.

 
#include <iostream>
 
using namespace std;
 
class A {
public:
    void funcA(void) {;}
};
 
class B {
public:
    void funcB(void) {;}
};
 
int main() {
    
    A *a = new A();
    B *b = reinterpret_cast<B*>( a );
 
    return 0;
}
 

 

 #4 ) const_cast< T >( ... )

 

 
#include <iostream>
 
using namespace std;
 
int main() {
    
    const char str[] = "TEST";
    char* c = const_cast<char*>( str );
    
    return 0;
}
 

 

arrow
arrow

    Cuby 56 發表在 痞客邦 留言(0) 人氣()