반응형
  • Down Casting
    • upcasting된 포인터를 원래의 타입으로 캐스팅 하는것
  • static_cast
    • 컴파일시간 캐스팅
    • 기반 클래스의 포인터가 실제 어떤 타입의 객체를 가리키는지 조사 할 수 없음
  • dynamic_cast
    • 실행시간 캐스팅
    • 잘못된 down casting 사용시 0 반환
    • 가상 함수가 없는 타입은 dynamic_cast를 사용할 수 없음
#include <iostream>
#include <typeinfo>
#include <typeindex>

class Animal 
{
public:
    virtual ~Animal() {}

};
class Dog : public Animal 
{
public:
    int color;
};

void foo(Animal* p)
{
    // 선 타입 비교, 후 static_cast
    if (typeid(*p) == typeid(Dog))
    {
        Dog* pDog = static_cast<Dog*>(p);
    }

    //OR

    // 선 dynamic_cast, 후 nullptr 비교
    Dog* pDog = dynamic_cast<Dog*>(p);
    if (pDog == nullptr)
    {
        std::cout << "nullptr" << std::endl;
    }

    std::cout << pDog << std::endl;

}

int main()
{
    Animal a; foo(&a);
    Dog d; foo(&d);
}

RTTI를 사용하지 않고 추가 기능을 제공하는 방법도 생각 필요

#include <iostream>

class Animal 
{
public:
    virtual ~Animal() {}
};
class Dog : public Animal
{
};

void foo(Animal* p)
{
}

void foo(Dog* p)
{
    foo(static_cast<Animal*>(p)); // 기존 공통 함수 기능 지원
    // Dog에 대한 특정 기능은 여기 추가 구현
}

int main()
{
    Animal a; foo(&a);
    Dog d; foo(&d);
}
반응형

+ Recent posts