在 C++ 中查找对象的类型

Finding the type of an object in C++(在 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++ 中查找对象的类型

基础教程推荐