nakka soft world !

RTTI ( Rut Time Type Information ) , dynamic_cast 본문

프로그래밍언어/C++

RTTI ( Rut Time Type Information ) , dynamic_cast

nakka 2017. 3. 27. 19:12
728x90

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);

}



728x90
Comments