아담 님이 쓰신 글 :
: 김백일 님이 쓰신 글 :
: : 아담 님이 쓰신 글 :
: : : TList안에 여려형의 객체가 들어있습니다.
: : :
: : : 그안의 객체를 가져올때 미리 형을 알아야 하는데
: : : 어떻게 알수 있나요
: : : 리스트박스의경우는
: : : ClassRef = Listbox->Items->Objects[Index]->ClassType();
: : :
: : : 어쩌구 저쩌구하던데
: : : 이건되는데 TList는 어떻게하나요?
: :
: : List1 안에 TObject에서 상속받은 객체들이 들어있다면,
: :
: : (TObject*)(List1->Items[Index])->ClassType();
: :
: : 이렇게 하면 되지 않나요?
: :
: : 단, 저장된 객체들이 TObject의 자손들이 아니라면 불가능한 방법이지요.
: :
: :
:
:
: 답변감사합니다 ^^ 그런데 객체는 제가 만든 클레스이고요 TObject의 자손들이 아니랍니다 ㅠㅠ
:
TList에 여러가지 타입의 객체를 저장하는 것(heterogeneous storage)과 같은
경우에는 RTTI(Runtime type Indentification)를 써야겠지요.
방법은 다음 3가지 입니다.
(1) heterogeneous storage가 아닌,
homogeneous storage(동일한 타입의 객체만 저장)인 경우로 알고리듬 자체를 바꾸는 방법이 있습니다.
(2) TObject::ClassType()과 같은 VCL의 RTTI를
사용하시려면 객체가 TObject의 자손이어야 합니다.
기존의 클래스 코드를 약간 수정하셔서,
베이스 클래스를 TObject로 바꿔보시면 될 겁니다.
(3) ANSI C++ 자체의 RTTI를 사용하는 방법이 있습니다.
typeid 라는 연산자는 type_info 클래스의 참조를 리턴합니다.
namespace std //class type_info is declared in namespace std
class type_info
{
public:
virtual ~type_info(); // type_info는 기저클래스로 사용된다
bool operator==(const type_info& rhs ) const; // enable comparison
bool operator!=(const type_info& rhs ) const; // return !( *this == rhs)
bool before(const type_info& rhs ) const; // ordering
const char* name() const; // 타입이름을 포함하는 C-string 반환
private:
// 이러한 타입의 객체들은 복사될 수 없다
type_info(const type_info& rhs );
type_info& operator=(const type_info& rhs);
}; //type_info
자세한 내용은 빌더 헬프를 참고하세요.
http://www.milab.co.kr/sub_lecture_cpp5_page3.htm
에도 자세한 설명이 있네요.
다음은 빌더 헬프의 예제입니다.
// HOW TO USE operator typeid, Type_info::before(), AND Type_info::name()
#include <iostream>
#include <typeinfo.h>
using std::cout;
using std::endl;
class A { };
class B : A { };
void main() {
char C;
float X;
// USE THE type_info::operator==()TO MAKE COMPARISON
if (typeid( C ) == typeid( X ))
cout << "C and X are the same type." << endl;
else cout << "C and X are NOT the same type." << endl;
// USE true AND false LITERALS TO MAKE COMPARISON
cout << typeid(int).name();
cout << " before " << typeid(double).name() << ": " <<
(typeid(int).before(typeid(double)) ? true : false) << endl;
cout << typeid(double).name();
cout << " before " << typeid(int).name() << ": " <<
(typeid(double).before(typeid(int)) ? true : false) << endl;
cout << typeid(A).name();
cout << " before " << typeid(B).name() << ": " <<
(typeid(A).before(typeid(B)) ? true : false) << endl;
}
[Program Output]
C and X are NOT the same type.
int before double: 0
double before int: 1
A before B: 1
-----------------------------------------------------------------------------------
PS) 가능한 한 TObject::ClassType()이나 typeid를 쓰는 방법 대신에
dynamic_cast 를 쓰는 방법이 더 좋습니다.
try ... catch 문에서 std::bad_cast 예외를 잡아내면 되지요.
제가 위에 적은 링크에도 자세한 설명이 있습니다.