글
typeid 키워드
Programming/C++ Language
2014. 4. 15. 13:36
typeid 키워드는 런타임에 오브젝트의 클래스를 결정하기 위해 사용 된다. std::type_info 오브젝트를 리턴한다.( 프로그램 종료까지 유지 되는 값 ) 단순히 class 정보만이 필요할 경우에, dynamic_cast<class_type> 보다는 typeid 를 사용하는 것을 선호한다.( typeid 의 수행속도가 짧음 )
#include <iostream> // cout #include <typeinfo> //for 'typeid' class Person { public: // ... Person members ... virtual ~Person() {} }; class Employee : public Person { // ... Employee members ... }; int main() { Person person; Employee employee; Person* ptr = &employee; Person& ref = employee; // The string returned by typeid::name is implementation-defined std::cout << typeid(person).name() << std::endl; // Person (statically known at compile-time) std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time) std::cout << typeid(ptr).name() << std::endl; // Person* (statically known at compile-time) std::cout << typeid(*ptr).name() << std::endl; // Employee (looked up dynamically at run-time // because it is the dereference of a // pointer to a polymorphic class) std::cout << typeid(ref).name() << std::endl; // Employee (references can also be polymorphic) Person* p = nullptr; try { typeid(*p); // not undefined behavior; throws std::bad_typeid // *p, *(p), *((p)), etc. all behave identically } catch (...) {} Person& pRef = *p; // Undefined behavior: dereferencing null typeid(pRef); // does not meet requirements to throw std::bad_typeid // because the expression for typeid is not the result // of applying the unary * operator }
Output (exact output varies by system):
Person Employee Person* Employee Employee
출처 : http://en.wikipedia.org/wiki/Typeid
'Programming > C++ Language' 카테고리의 다른 글
static_cast 와 dynamic_cast (0) | 2015.01.07 |
---|---|
warning 에 대하여 (0) | 2015.01.07 |
Unique Pointer (0) | 2014.03.03 |
[C++] 동적바인딩( Dynamic binding ) (0) | 2011.01.03 |
[C++] this 포인터 사용하기 (0) | 2010.07.31 |