nakka soft world !
RTTI ( Rut Time Type Information ) , dynamic_cast 본문
RTTI ( Rut Time Type Information )
#include <typeinfo>
void foo(Animal* p)
{
// p가 실제로 어떤 객체를 가리킬까?
// RTTI
const type_info& t1 = typeid(*p);
const type_info& t2 = typeid(Dog);
if (t1 == t2) {}
if(typeid(*p) == typeid(Dog))
{
// p를 Dog타입으로 캐스팅 해서 사용
Dog* pDog = static_cast<Dog*>(p);
// pDog->Dog고유 멤버 = 10;
}
}
int main()
{
Animal a;
foo(&a);
Dog d;
foo(&d);
}
RTTI는 사용하지 않는 것이 좋은 디자인이다.
dynamic_cast
class Animal
{
public:
int age;
virtual ~Animal(){} // dynamic_cast를 위해서는 하나이상의 가상함수 필요.
};
class Dog : public Animal
{
public:
int color;
};
void foo(Animal* p)
{
// const type_info& t = typeid(*p);
// 컴파일 시간에 캐스팅 하므로 객체 조사 불가.
// Dog* pDog = static_cast<Dog*>(P);
// cout << pDog << endl;
// 실행 시간에 캐스팅 함.
Dog* pDog = dynamic_cast<Dog*>(P); // dynamic_cast를 위해서는 하나이상의 가상함수 필요.
if(pDog != 0)
{
pDog->color = 10;
}
}
int main()
{
Animal a;
foo(&a);
Dog d;
foo(&d);
}
'프로그래밍언어 > C++' 카테고리의 다른 글
예외 (Exception) (0) | 2017.03.27 |
---|---|
다중 상속 (multiple inheritance), 다이아몬드 상속 (0) | 2017.03.27 |
함수 바인딩과 가상함수의 원리 (0) | 2017.03.27 |
추상클래스와 인터페이스 (0) | 2017.03.27 |
순수 가상 함수와 추상 클래스 (0) | 2017.03.27 |