Run-time type information in C++

和自甴很熟 提交于 2019-12-06 02:14:34

问题


What is runtime type control in C++?


回答1:


It enables you to identify the dynamic type of a object at run time. For example:

class A
{
   virtual ~A();
};

class B : public A
{
}

void f(A* p)
{
  //b will be non-NULL only if dynamic_cast succeeds
  B* b = dynamic_cast<B*>(p);
  if(b) //Type of the object is B
  {
  }
  else //type is A
  { 
  }
}

int main()
{
  A a;
  B b;

  f(&a);
  f(&b);
}



回答2:


It is not just about dynamic_cast, but the entire RTTI is part of it. The best place to learn about RTTI is section 15.4 of the C++ Programming Language by Bjarne Stroustrup




回答3:


It's dynamic_cast functionality - your code can detect at runtime if a given pointer or reference is really bound to an object of type you expect.




回答4:


The correct name of this is Run-time type information (RTTI).




回答5:


You can take a Interface* and "ask" c++ to what type of object the pointer points. To my knowledge, this relies on runtime meta information, that needs a few cycles for storing and searching such information.

Look at the "typeid" keyword. It provides the most magic.

dynamic_cast only uses RTTI, typeid with std::type_info seems to me more like the "real thing".



来源:https://stackoverflow.com/questions/1409890/run-time-type-information-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!