코스웨어/14년 스마트컨트롤러
20141112 업무일지 출석번호 10번 김화린
알 수 없는 사용자
2014. 11. 12. 16:44
C++
641 page
reinterpret_cast:상관없는 자료형으로 형 변환
int main() { SimpleCar* car = new Cae; BestFriend * fren = reinterpret_cast<BestFriend*>(car); } |
|
객체 타입을 완전히 바꾸는 것을 reinterpret_cast 라고한다.
642_ReinterpretCasting.cpp
#include <iostream> using namespace std;
int main() { int num = 0x010203; char * ptr = reinterpret_cast<char * >(&num);
for(int i =0; i < sizeof(num); i++) { cout << static_cast<int>(*(ptr+i) ) << endl; }
return 0; } |
|
이소스는 reinterpret를 허용해야 되는 것.
hexa view 쓸 때 이렇게 type변환이 필요하다.
644_PolymorphicDynamicCasting.cpp
가상함수를 가지고 있어서 허용 635page의 소스를 보면
Car * pcar1 = new Truck(80, 200); Truck * ptruck1 = dynamic_cast<Truck*> (pcar1); |
|
거의동일한 수준의 애를 캐스팅허용하는 dynamic이지만
여기서 허용하는 것은 가상함수를 가지고 있기 때문이다.
646page
int main() { SoSimple * simPtr = new SoSimple; SoComplex *comPtr = dynamic_cast<SoComplex*>(simPtr); } |
|
부모 * A = 부모 객체;
자식 * B = 캐스팅(A);
이것은
가상함수가 있으면 컴파일은 시켜주지만 NULL을 반환하게 된다.
635page 의
Car * pcar2 = new Car(120); Truck * ptruck2 = dynamic_cast<Truck* > (pcar2); |
|
은 에러가 나지만
646_PolymorphicStableCasting.cpp
#include <iostream> using namespace std;
class SoSimple //polymorphic클래스! ShowSimpleInfo가 가상함수이므로 { public: virtual void ShowSimpleInfo() { cout <<"SoSimple Base Class" << endl; } };
class SoComplex : public SoSimple { public: void ShowSimpleInfo() //이것 역시 가상함수! { cout <<"SoComplex Derived Class" << endl; } };
int main() { SoSimple * simPtr = new SoSimple; SoComplex* comPtr = dynamic_cast<SoComplex*>(simPtr); if(comPtr==NULL) { cout<<"형 변환 실패" << endl; } else { comPtr->ShowSimpleInfo(); } return 0; } |
|
에러가 나지 않는다.
NULL을 반환해서 실행을 시켜준다. 안전성을 검사하도록 컴파일러가 바이너리 코드를 생성한다. 실행속도는 늦어지지만(가상함수는 가상테이블을 만들기 때문에) 그만큼 안정적이다.
RunTime중에 결정이 된다. 실행중간에 캐스팅이 결정되니깐 dynamic_cast 이고 이것의 반대 개념이 static_cast이다. 빠른 것은 static이 빠르다.
647_DynamicBadCastRef.cpp
#include <iostream> using namespace std;
class SoSimple { public: virtual void ShowSimpleInfo() //virtual 선언하지 않으면 컴파일이 안된다. { cout <<"SoSimple Base Class" << endl; } };
class SoComplex : public SoSimple { public: void ShowSimpleInfo() { cout<<"SoComplex Derived Class" << endl; } };
int main() { SoSimple simObj; SoSimple& ref = simObj;
try { SoComplex& comRef = dynamic_cast<SoComplex&>(ref); comRef.ShowSimpleInfo(); } catch(bad_cast expt) { cout << expt.what()<<endl; }
return 0; } |
|
이것은 캐스팅이 아니고 예외이다.
C++끝!!