gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:16:40 28 4
gpt4 key购买 nike

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

Base* b = new Derived():

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

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

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

最佳答案

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


顺便提一下, typeid call 是 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 typeid expression throws the std::bad_typeid exception (18.7.3).”

关于c++ - 如何在 C++ 中确定运行时的实际对象类型;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15898121/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com