如何在C ++中确定运行时的实际对象类型; [英] How to determine actual object type at runtime in C++;

查看:222
本文介绍了如何在C ++中确定运行时的实际对象类型;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我们有一个类层次结构.在底部有Base,在顶部有Derived. 即使转换为基类指针也如何确定对象类.

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* b = new Derived():

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

除了手动实现字符串字段或虚拟get函数以外,还有其他方法吗?

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

PS:我说的是与编译器无关的解决方案

PS: I talking about compiler-independent solution

推荐答案

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


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

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().


in passing, note that a typeid call is the one place in C++ where you can dereference a nullpointer with well-defined behavior, which implies that it can throw an exception:

C ++ 11§5.2.8/2 :
“如果glvalue表达式是通过将一元*运算符应用于a 指针,并且指针是空指针值(4.10),typeid表达式将引发std::bad_typeid异常(18.7.3).

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 typeid expression throws the std::bad_typeid exception (18.7.3).”

这篇关于如何在C ++中确定运行时的实际对象类型;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆