cpp中typeid

来源:互联网 发布:自己没货如何开淘宝店 编辑:程序博客网 时间:2024/05/01 10:37

cpp中typeid举例:

#include <iostream>#include <typeinfo>  //for 'typeid'using namespace std;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 = 0;   try {        typeid(*p); // not undefined behavior; throws std::bad_typeid                  // *p, *(p), *((p)), etc. all behave identically   }catch (...){        cout << "NULL pointer!"<<endl;   }  Person& pRef = *p; // undefined behavior, dereferences null  typeid(pRef);        // does not meet requirements to throw std::bad_typeid  Employee e;  Person pp;  Person &per_ref = pp;  try{    Employee & em_ref = dynamic_cast<Employee&>(per_ref);  }catch(bad_cast e){    cout << "bad cast : not valid type reference !" <<endl;  }catch(...){    cout << "not valid type reference !" <<endl;  }                    // because the expression for typeid is not the result                      // of applying the unary * operator; behavior is undefined}


原创粉丝点击