ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Type Cast
    프로그래밍/C and C++ 2005. 6. 21. 19:21

    MFC 나 템플릿 관련

    소스를 보면 좀 낯설은 코드를 볼수 있습니다.

     

    이 낯설은 코드중에  ?_cast 라는 키워드에

    대해서  말하고자 합니다 . 이 키워드는 표준 c++에서

    특이할 만한 것들입니다. 아래 설명되어진 내용이 정확한지 모르겠습니다.

    더 좋은 설명이 있으면 뎃글로 남겨 주세요......

     

     

    타입변환(cast)
    static_cast( 보편적인 타입 변환 )
    const_cast( 상수 타입 변환 )
    dynamic_cast( 상속 계층과 관련된 타입 변환: 제5장 참조 )
    reinterpret_cast( 포인터 타입 변환 )

     

    ----------------------------

    static_cast
    다른 타입으로의 변환
     일반적인 타입변환


    C에서의 타입변환
          average = ( float ) hits / ( float ) at_bats;


    C++에서의 타입변환
          average = static_cast<float>( hits )/ static_cast<float>( at_bats );


    구문
    static_cast<target-type>( source-expression )

     

     

    ----------------------------

    const_cast
      상수 타입을 변환할 때 사용
      const 객체에 대한 포인터를 const가 아닌 객체의 포인터로 변환할 때 사용


    #include <iostream>
    using namespace std;


    const int* find( int val, const int* t, int n );


    int main() {
        int a[ ] = { 2, 4, 6 };
        int* ptr;
        ptr = const_cast<int*>( find( 4, a, 3 ) );
        // …
    }

     

     

    ----------------------------------

    reinterpret_cast


    다른 타입의 포인터로 변환하거나 포인터 타입을 정수 타입으로 변환


    주의: 구현에 종속적


        int i;
        float f = -6.9072;


        unsigned char* p =reinterpret_cast<unsigned char*>(&f);


        cout << hex; // print bytes of f in hex
        for ( i = 0; i < sizeof( float ); i++ )
            cout << static_cast<int>(p[ i ]) << \n;

     

    ----------------------------------

    dynamic_cast

     dynamic_cast는 상위클래스 포인터를 하위클래스 포인터로 변환할때 사용하거나 void형 포인터를 변환할때 사용한다.

     

    dynamic_cast<type-id>(expression)

     

    (ex)

    A* pa = new A;
    void* pv = dynamic_cast<void*>(pa);

    type-id 는 포인터이거나 레퍼런스여야한다. ex)에서 pv포인터는 A 타입의 오브젝트를 가리키게 된다. 또한 변환 가능 여부가 런타임에 체크된다.변환 가능하면 변환된 포인터를 리턴하고 불가능하면 NULL을 리턴한다

    댓글