如何在 C++ 中在运行时确定实际对象类型;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15898121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:52:34  来源:igfitidea点击:

How to determine actual object type at runtime in C++;

c++typeidtypeinfo

提问by user1079475

Lets say we have a class hierarchy. At the bottom we have Base and at the top Derived. How to determine object class even if it is converted to base class pointer.

假设我们有一个类层次结构。在底部,我们有 Base,在顶部有 Derived。即使将对象类转换为基类指针,如何确定对象类。

Base* b = new Derived():

typeid(b).name(); // i want this to tell me that this is actually derived not base object

is there any way other than manual implementation of string field or such and virtual get function?

除了手动实现字符串字段或此类和虚拟获取功能之外,还有其他方法吗?

PS: I talking about compiler-independent solution

PS:我说的是独立于编译器的解决方案

回答by Cheers and hth. - Alf

make sure the base class has at least one virtual method, include <typeinfo>and use your current code just with an additional dereferencing, typeid(*b).name().

确保基类至少有一个虚方法,包括<typeinfo>并使用您当前的代码,只需附加一个解引用,typeid(*b).name().



顺便说一下,请注意,typeidtypeid调用是 C++ 中可以取消引用具有明确定义行为的空指针的地方,这意味着它可以抛出异常:

C++11 §5.2.8/2:
“If the glvalue expression is obtained by applying the unary *operator to a pointer and the pointer is a null pointer value (4.10), the typeidexpression throws the std::bad_typeidexception (18.7.3).”

C++11 §5.2.8/2
“如果泛左值表达式是通过将一元运算*符应用于指针获得的,并且该指针是空指针值 (4.10),则typeid表达式将引发std::bad_typeid异常 (18.7.3)。”

回答by Angew is no longer proud of SO

If all you want to do is find if bactually points to Derived, just use dynamic_cast():

如果您只想查找是否b实际指向Derived,只需使用dynamic_cast()

if (dynamic_cast<Derived*>(b)) { ... }

dynamic_castreturns a null pointer if the actual runtime type of the object pointed to by bis not Derived(or a class derived from Derived). Unlike the name()member of std::type_info, this is compiler-invariant.

dynamic_cast如果指向的对象的实际运行时类型b不是Derived(或派生自 的类Derived),则返回空指针。与 的name()成员不同std::type_info,这是编译器不变的。

Note that this only works if Basehas at least one virtual member functions. Which it should anyway, since you're manipulating types derived from it through a base pointer, so it should have a virtual destructor.

请注意,这仅在Base具有至少一个虚拟成员函数时才有效。无论如何它应该是,因为您通过基指针操作从它派生的类型,所以它应该有一个虚拟析构函数。