4、dynamic_cast
dynamic_cast用于子类和父类之间的转换,它可以将父类的指针或引用转换为子类的指针或引用。
dynamic_cast与前三种强制转换不同,它涉及运行时类型检查。如果绑定到引用或指针的类型对象不是目标类型的对象时,则dynamic_cast失败。当用于指针的转换失败时,dynamic_cast的结果为0,用于引用的转换失败时,则抛出一个bad_cast异常。
可用下面例子所用的结构对转换进行检测:
指针转换:
if(Derived *derviedPtr = dynamic_cast<Derived*>(basePtr){ // use the Derived object to which derivedPtr points } else{ // basePtr oiubsts at a Base object // use the Base object to which basePtr points } |
引用转换:
void f(const Base& b) { try{ const Derived& d = dynamic_cast<const Derived&>(b); // use the Derived object to which b referred } catch (bad_cast){ // handle the fact that the cast failed } } |
至此,转换操作符介绍完毕。