static_cast와 reinterpret_cast 예제로 본 차이
#include "stdafx.h"
#include <stdio.h>
class shape{
private:
int a;
public:
virtual void draw() { printf("share::draw() \n"); }
};
class rect : public shape {
private:
int b;
public:
rect() { b = 30; }
void draw() { printf("rect::draw() \n"); }
void onlyRect() { printf("rect::onlyRect() \n"); }
};
int _tmain(int argc, _TCHAR* argv[])
{
int arData[] = {1,2,3,4};
int * ptr = static_cast<int *>(arData);
char * pStr = "ABC";
ptr = static_cast<int *>(pStr); // error C2440: 'static_cast' : 'char *'에서 'int *'(으)로 변환할 수 없습니다.
rect rcTest;
shape * pShare = static_cast<shape *>(&rcTest); // upcast
pShare->draw();
shape parent;
rect * pRect = static_cast<rect *>(&parent); // downcast
pRect->draw();
pRect->onlyRect();
int nData = 0x12345678;
ptr = reinterpret_cast<int *>(nData); // 단순무식하게 ptr은 0x12345678 주소임
printf( "ptr(%p) \n", ptr );
int * ptr2 = &nData;
char * pChar = reinterpret_cast<char *>(ptr2);
printf( "ptr2(%p), pChar(%p) \n", ptr2, pChar );
return 0;
}
static_cast<>
포인터 타입을 다른 타입으로 변환시 컴파일단계에서 위와 같이 에러를 보여준다
상속관계에 있는 포인터끼리 변환은 허용됨. upcast의 경우는 문제가 없으나 downcast의 경우는 unsafe하게 동작할 수 있다.
reinterpret_cast<>
임의의 포인터끼리 변환 허용
#include <stdio.h>
class shape{
private:
int a;
public:
virtual void draw() { printf("share::draw() \n"); }
};
class rect : public shape {
private:
int b;
public:
rect() { b = 30; }
void draw() { printf("rect::draw() \n"); }
void onlyRect() { printf("rect::onlyRect() \n"); }
};
int _tmain(int argc, _TCHAR* argv[])
{
int arData[] = {1,2,3,4};
int * ptr = static_cast<int *>(arData);
char * pStr = "ABC";
ptr = static_cast<int *>(pStr); // error C2440: 'static_cast' : 'char *'에서 'int *'(으)로 변환할 수 없습니다.
rect rcTest;
shape * pShare = static_cast<shape *>(&rcTest); // upcast
pShare->draw();
shape parent;
rect * pRect = static_cast<rect *>(&parent); // downcast
pRect->draw();
pRect->onlyRect();
int nData = 0x12345678;
ptr = reinterpret_cast<int *>(nData); // 단순무식하게 ptr은 0x12345678 주소임
printf( "ptr(%p) \n", ptr );
int * ptr2 = &nData;
char * pChar = reinterpret_cast<char *>(ptr2);
printf( "ptr2(%p), pChar(%p) \n", ptr2, pChar );
return 0;
}
static_cast<>
포인터 타입을 다른 타입으로 변환시 컴파일단계에서 위와 같이 에러를 보여준다
상속관계에 있는 포인터끼리 변환은 허용됨. upcast의 경우는 문제가 없으나 downcast의 경우는 unsafe하게 동작할 수 있다.
reinterpret_cast<>
임의의 포인터끼리 변환 허용
댓글
댓글 쓰기