본문 바로가기

Native/C++

실시간 타입 정보(don

타입 정보

실행중에 타입을 판별할 수 있는 기능이 필요해진 것이다 C++의 초기 스팩에는 포함되지 않았다. . 그래서 컴파일러 제작사나 라이브러리 제작사들은 나름대로 실행중에 객체의 타입을 판별할 수 있는 기능을 작성해서 이미 사용했다. MFC의 경우 루트 클래스인 CObject에 객체의 타입을 저장하는 멤버와 타입을 판별하는 IsKindOf, IsDerivedFrom 함수들이 포함되어 있다.

하지만 컴파일러 업체에서 만든 부분이기에 호환성이 결여되었기에 최신 C++에 포함되었고 RTTI가 바로 실시간 타입 정보를 알려주는 녀석이다.

그리고 RTTI 기능은 typeid연산자로 사용이 된다. 이 연산자는 클래스의 이름이나 객체 또는 객체를 가리키는 포인터를 피연산자로 취하며 피연산자의 타입을 조사한다.

[code]
#include <Turboc.h>

class Parent
{
public:
    virtual void PrintMe() { printf("I am Parent\n"); }
};

class Child : public Parent
{
private:
    int num;

public:
    Child(int anum=1234) : num(anum) { }
    virtual void PrintMe() { printf("I am Child\n"); }
    // 이 상황에서는 PrintNum이 제대로 작동 되지 않는다.
    // 만약 이곳에 virtual을 붙이게 된다면 -_- 불행이도 프로그램이 조용히
    // 메모리 에러를 내면서 다운된다. 으흐 ~
    void PrintNum() { printf("Hello Child=%d\n",num); }
};

void func(Parent *p)
{
    p->PrintMe();
    ((Child *)p)->PrintNum();
}

void main()
{
    Parent p;
    Child c(5);

    func(&c);
    func(&p);
}
[/code]

typeid 응용 프로그램

[code]
#include <Turboc.h>
#include <typeinfo>

class Parent
{
public:
    virtual void PrintMe() { printf("I am Parent\n"); }
};

class Child : public Parent
{
private:
    int num;

public:
    Child(int anum=1234) : num(anum) { }
    virtual void PrintMe() { printf("I am Child\n"); }
    void PrintNum() { printf("Hello Child=%d\n",num); }
};

void main()
{
    Parent P,*pP;
    Child C,*pC;
    pP=&P;
    pC=&C;

    printf("P=%s, pP=%s, *pP=%s\n",
        typeid(P).name(),typeid(pP).name(),typeid(*pP).name());
    printf("C=%s, pC=%s, *pC=%s\n",
        typeid(C).name(),typeid(pC).name(),typeid(*pC).name());

    pP=&C;
    printf("pP=%s, *pP=%s\n",
        typeid(pP).name(),typeid(*pP).name());
}[/code]