C ++等同于Java的instanceof [英] C++ equivalent of java's instanceof

查看:89
本文介绍了C ++等同于Java的instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现与Java的instanceof等效的C ++的首选方法是什么?

What is the preferred method to achieve the C++ equivalent of java's instanceof?

推荐答案

尝试使用:

if(NewType* v = dynamic_cast<NewType*>(old)) {
   // old was safely casted to NewType
   v->doSomething();
}

这需要您的编译器启用rtti支持.

This requires your compiler to have rtti support enabled.

我对这个答案有很好的评论!

I've had some good comments on this answer!

每次需要使用dynamic_cast(或instanceof)时,最好问问自己是否必要.通常,这是设计不佳的标志.

Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.

典型的变通办法是将要检查的类的特殊行为放入基类的虚函数中,或者可能引入访问者,您可以在不更改接口的情况下为子类引入特定的行为(当然,添加访问者接受接口除外).

Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).

如前所述,dynamic_cast不是免费提供的.一个处理大多数(但不是所有情况)的简单且性能一致的hack基本上是添加一个枚举,表示您的类可以拥有的所有可能的类型,并检查您是否找到了正确的类型.

As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.

if(old->getType() == BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

这不是一个好的设计,但它可能是一种解决方法,其成本或多或少只是一个虚拟函数调用.无论是否启用了RTTI,它都可以工作.

This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.

请注意,这种方法不支持多级继承,因此,如果您不小心,可能会以如下代码结尾:

Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:

// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

这篇关于C ++等同于Java的instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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