일자 98/ 6/12 [금] 12:22 pm KST
  이름 정희석(heesc)[heesc@shinbiro.com]                                                                                                        
  제목 [답변] RTTI 예제


RTTI 란 말 그대로 실시간에 객체 타입 ( 계층 이름 )을 알아내는
기능입니다. 대체로 이 내용은 예외처리 부분에 제시됩니다. 저로서는
그럴듯한 응용예를 찾진 못했고요, 아래와 같이 예제를 위한 예제를
작성했습니다. 이 코드는 GNU C++ (DJGPP) 과 볼랜드 C++ 4.0 으로
테스트 됐습니다.이걸 예제를 위한 예제라고 말씀드리는 이유는
아래같은 예외처리는 가상함수를 사용하면 보다 효율적으로 작성될
수 있기 때문입니다.
매우 복잡하게 얽힌 계승 체계하에서 RTTI 가 객체 무결성을 보장
하는데 장점을 줄 수 있을 것 같습니다. 하지만 RTTI 는 객체들이
실시간 타입정보를 가질 수 있도록 부가적인 메모리를 확보할 것입니다.

/*
RTTI example
1998. 6. 8
Hee S. Chung
hee@cyberkorea.com

GNU compiler :
  gxx -frtti -fhandle-exceptions f:rtti.cpp
*/

// inclusion for RTTI
#if defined(__GNUC__)

#include
#include

#else

#ifdef __TURBOC__
#if __BCPLUSPLUS__<0x320
  #error RTTI not supported
#endif
#else
#error check your compiler manual for typeinfo.h and cstring.h
// 비쥬얼 컴파일러 등을 사용하고 있다면 이들과 상응하는 헤더파일이
// 필요합니다.
#endif

#include
#include

#endif

#include

// classes defined for this example
class A
{
public :
// following virtual function makes polymorphic class A
virtual void exception( void ){}
};

class B : public A
{
};

class X
{
protected :
int a;
};

class C : public A, public X
{
};

/*
  Borland compiler supports __rtti keyword to force RTTI when -RT-
option ( disable RTTI ) is used.
class __rtti RTTI_CLASS
{
public :
  virtual int doit( void ){ return 1; }
};
*/

void main( void )
{
C c;
A* p = &c;

try
{
  //  Assume we don't know which pointer of object was initialized
  // into pointer 'p'. If only the object created by class A or B is
  // allowed to perform next routines, we can get real-time type
  // information by following codes.
  // 포인터 p 에 어떤 객체의 포인터가 초기화됐는지 모른다고
  // 가정합니다. 다음 과정을 행하는데, 계층 A 와 B 에 의해 생성된
  // 객체만 허용된다면 다음과 같이 실시간 타입 정보를 얻을 수
  // 있습니다.
  if( typeid(*p)!=typeid(A) && typeid(*p)!=typeid(B) )
  {
   // 예외 객체를 던집니다.
   throw string( typeid(*p).name() );
  }

  // do something with 'p'
}
catch( string name )
{
  cout << "exception : class " << name << " is used\n";
}
}

'KB > C/C++' 카테고리의 다른 글

dos에서 vga13h 쓰기  (0) 2004.03.19
this에 대하여  (0) 2004.03.19
tc 라이브러리 만들기  (0) 2004.03.19
비트 연산  (0) 2004.03.19
C&ASM  (0) 2004.03.19

+ Recent posts