关于dynamic_cast的简单笔记

最近想了解下c++中继承和多态的细节问题,其中一个需要理解的是dynamic_cast这个强制类型转换key-word。dynamic_cast用于多态类型间的类型转换,在需要的时候提供运行时检测,即检查类型转换是否可行的。

一个派生类的指针或者引用转换成父类的指针或引用总是可行的,所以使用dynamic_cast一定会成功。

但是一个父类的指针或者引用转换成派生类的指针或者引用不一定是可行的,除非父类指针指向的是派生类或者派生类的子孙的实例。这时使用就要使用dynamic_cast来进行强制类型转换以检测是否可行,对于指针的转换,如果不可行,则转换后的结果为NULL;对于引用的转换,如果不可行,则抛出std::bad_cast异常。(因为不捕捉异常的话程序会调用特定的函数然后推出,具体是啥不太记得了,所以看来在多态中的类型使用引用还是会有隐患的)。

具体的资料是在http://en.cppreference.com/w/cpp/language/dynamic_cast看到的。

If the casted type is a pointer, the pointed object is checked whether it is the requested base class. If the check succeeds, pointer to the requested base class is returned, otherwise NULL pointer is returned.

If the casted type is a reference, the pointed object is checked whether it is the requested base class. If the check succeeds, reference to the requested base class is returned, otherwise std::bad_cast is thrown.

一个抄来的示例

#include <iostream>

struct Base {
virtual ~Base() {}
virtual void name() {}
};

struct Derived: Base {
virtual ~Derived() {}
virtual void name() {}
};

struct Some {
virtual ~Some() {}
};

int main()
{
Some *s = new Some;
Base* b1 = new Base;
Base* b2 = new Derived;

Derived *d1 = dynamic_cast<Derived*>(b1);
Derived *d2 = dynamic_cast<Derived*>(b2);
Derived *d3 = dynamic_cast<Derived*>(s);
Base *d4 = dynamic_cast<Base*>(s);

std::cout << "'b1' points to 'Derived'? : " << (bool) d1 << '\n';
std::cout << "'b2' points to 'Derived'? : " << (bool) d2 << '\n';
std::cout << "'s' points to 'Derived'? : " << (bool) d3 << '\n';
std::cout << "'s' points to 'Base'? : " << (bool) d4 << '\n';
}

输出:

i = 4
type::i = 4
'b1' points to 'Derived'? : false
'b2' points to 'Derived'? : true
's' points to 'Derived'? : false
's' points to 'Base'? : false

posted on 2012-02-15 16:30  Qwertycen  阅读(506)  评论(0编辑  收藏  举报

导航