源于《Practical Java》中实践5/6。
啥时候才需要使用 instanceof 呢?唯一的情况:基类向子类 dynamic cast 的时候。
class A;
class B extends A;
class C extends A;
class D;
A a = new B();
B b = (B) a; // ok
C c = (B) a; // runtime error (throw ClassCastException)
D d = (D) a; // compile error
只有下面的情况,才需要 instanceof,不过应该避免“同一基类下各个子类有不同行为"这样的设计存在。
for ( o : ArrayOfTypeA )
{
if ( o instanceof B ) { B b = (B)o; ... do sth. B-specific }
else if ( o instanceof C ) { C c = (C)o; ... do sth. C-specific }
...
}
对比 C++ 的 dynamic_cast<T>(p)class A { virtual void foo(){} };
class B : public A;
class C : public A;
class D;
C-style cast,一定成功,但转换过去,语义上说不同。
A *a = new C();
B *b = (B*)p;
D *d = (D*)p;
对于 T 为指针,转换不成功,则返回。所以这里 b/d 都等于 NULL。如果按 java 的规则,d 应该为 compile error。
B *b = dynamic_cast<B*>(a);
D *d = dynamic_cast<D*>(a);
对于 T 为引用,转换不成功,则 throw std::
bad_cast,T_T 居然于指针时的行为不一致。
C c;
A &a = c;
B &b = dynamic_cast<B&>(a);
D &d = dynamic_cast<D&>(a);
对于 T 为 void *,无论如何,都可以转换成功,b 就等于 a 的地址。
void *b = dynamic_cast<void*>(a);
参考资料
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htmhttp://en.wikipedia.org/wiki/Dynamic_casthttp://www.cppreference.com/wiki/keywords/dynamic_castps. 一件简单的事情,居然让 wikipedia 上有专贴,C++ 真是把简单的问题复杂化。目前觉得 C++ 中引入 reference(引用) 带来的复杂,远比其带来的便利大。
评论