简体   繁体   中英

Run-time type information in C++

什么是C ++中的运行时类型控件?

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);
}

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

它是dynamic_cast功能 - 您的代码可以在运行时检测给定的指针或引用是否真的绑定到您期望的类型的对象。

正确的名称是运行时类型信息(RTTI)

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM