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

查看:24
本文介绍了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.

典型的解决方法是将您正在检查的类的特殊行为放入基类的虚函数中,或者可能引入诸如 visitor 在这里你可以在不改变接口的情况下为子类引入特定的行为(当然除了添加访问者接受接口).

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
}

这不是一个好的 oo 设计,但它可以作为一种解决方法,其成本或多或少只是一个虚函数调用.无论 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天全站免登陆