반응형
    
    
    
  - 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);
}반응형
    
    
    
  '프로그래밍 언어 > C++' 카테고리의 다른 글
| C++ 예외처리(Exception), noexcept, try, catch, throw (0) | 2019.05.14 | 
|---|---|
| C++ 다중 상속(Multiple Inheritance), 가상 상속(Virtual Inheritance) (0) | 2019.05.12 | 
| C++ RTTI(Run Time Type Information), typeid, type_info (0) | 2019.05.12 | 
| C++ 가상 함수 테이블 (0) | 2019.05.12 | 
| C++ 함수 바인딩(Function Binding) (0) | 2019.05.12 |