在C ++中查找对象的类型 [英] Finding the type of an object in C++

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

问题描述

我有一个类A和从它继承的另一个类,B.我覆盖一个接受类型A的对象作为参数的函数,所以我必须接受一个A.然而,我稍后调用只有B有,所以我想返回假,如果传递的对象不是类型B,不继续。

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.

确保Base类中至少有一个虚函数dynamic_cast工作。

这篇关于在C ++中查找对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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