Finding the type of an object in C++(在 C++ 中查找对象的类型)
问题描述
我有一个类 A 和另一个继承自它的类 B.我正在覆盖一个接受类型 A 的对象作为参数的函数,所以我必须接受一个 A.但是,我后来调用的函数只B 有,所以如果传递的对象不是 B 类型,我想返回 false 并且不继续.
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.
找出传递给我的函数的对象是哪种类型的最佳方法是什么?
What is the best way to find out which type the object passed to my function is?
推荐答案
dynamic_cast 应该可以解决问题
dynamic_cast should do the trick
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
dynamic_cast 关键字从一个指针或引用类型指向另一个,执行运行时检查以确保转换的有效性.
The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast.
如果您尝试将指针强制转换为指向不是实际对象类型的类型,则强制转换的结果将为 NULL.如果您尝试强制转换为对不是实际对象类型的类型的引用,则该类型转换将抛出 bad_cast 异常.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception.
确保基类中至少有一个虚函数来使 dynamic_cast 工作.
维基百科主题运行时类型信息
RTTI 仅适用于多态的类,这意味着他们至少有一个虚拟方法.在实践中,这不是一个限制,因为基类必须有一个虚拟析构函数允许派生类的对象执行适当的清理,如果它们是从基指针中删除.
RTTI is available only for classes that are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because base classes must have a virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.
这篇关于在 C++ 中查找对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中查找对象的类型
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
