2. http://blog.naver.com/ruvendix
C++의 형식 선정 연산자
C++은 좀 더 안전하고 확실한 형식 선정을 위해
형식 선정 연산자를 4개나 제공하고 있음!
연산자 사용 빈도
static_cast 자주 사용함
dynamic_cast 잘 사용하지 않음
const_cast 잘 사용하지 않음
reinterpret_cast 적당히 사용함
3. http://blog.naver.com/ruvendix
static_cast
class CParent { };
class CChild : public CParent { };
// 상속 간의 형식 선정
CParent *pParent = static_cast<CParent *>(new CChild);
delete pParent;
CParent *pParent = static_cast<CChild *>(new CChild);
delete pParent;
// 이런 경우도 형식 선정 가능
CChild *pChild = static_cast<CChild *>(new CParent);
delete pChild;
4. http://blog.naver.com/ruvendix
dynamic_cast
class CParent { };
class CChild : public CParent { };
// 상속 간의 형식 선정
CParent *pParent = dynamic_cast<CParent *>(new CChild);
delete pParent;
CParent *pParent = dynamic_cast<CChild *>(new CChild);
delete pParent;
// 이런 경우는 형식 선정 불가능!
CChild *pChild = dynamic_cast<CChild *>(new CParent);
delete pChild;
5. http://blog.naver.com/ruvendix
const_cast
const int iNum = 100;
int *pNum = const_cast<int *>(&iNum);
iNum = 200; // 변경 불가능!
*pNum = 200; // 변경 가능!
// iNum의 값은 100
cout << iNum << endl;
// *pNum의 값은 200
cout << *pNum << endl;
6. http://blog.naver.com/ruvendix
reinterpret_cast
int iAddress = 0x12345678;
int *pAddress = reinterpret_cast<int *>(iAddress);
// hex는 16진수로 출력하는 것
// pAddress는 0x12345678
cout << hex << pAddress << endl;
int iNewAddress = reinterpret_cast<int>(pAddress);
// iNewAddress는 0x12345678
cout << iNewAddress << endl;