In the expression, dynamic_cast< T > (ptr), T must be a pointer or a reference to a defined class type or void*. The argument ptr must be an expression that resolves to a pointer or reference.
在这个表达式中,dynamic_cast< T > (ptr), T 必须是一个指针或一个引用类或Void指针,ptr变量必须是一个表达式才能够分解前面的指针或定义的类.
If T is void* then ptr must also be a pointer. In this case, the resulting pointer can access any element of the class that is the most derived element in the hierarchy. Such a class cannot be a base for any other class.
如果T是Void指针则ptr必须同样是一个指针.在这个格式里,作为结果的指针才能够访问在这个层次上的派生类中的元素.这一个类不能是任何其它类的基类.
Conversions from a derived class to a base class, or from one derived class to another, are as follows: if T is a pointer and ptr is a pointer to a non-base class that is an element of a class hierarchy, the result is a pointer to the unique subclass. References are treated similarly. If T is a reference and ptr is a reference to a non-base class, the result is a reference to the unique subclass.
从一个派生类转化为一个基类或其它的类,则有以下规定:假入T是一个指针,ptr指向一个不是基类的此层上的类元素.则结果指向一个唯一的子类.引用也一样,如果T是一个引用且Ptr是一派生类引用,则结果是子类引用.
A conversion from a base class to a derived class can be performed only if the base is a polymorphic type.
从基类转化为派生类(基类是多态性).
The conversion to a base class is resolved at compile time. A conversion from a base class to a derived class, or a conversion across a hierarchy is resolved at runtime.
If successful, dynamic_cast< T > (ptr) converts ptr to the desired type. If a pointer cast fails, the returned pointer is valued 0. If a cast to a reference type fails, the Bad_cast exception is thrown.
Note: Runtime type identification (RTTI) is required for dynamic_cast.
// HOW TO MAKE DYNAMIC CASTS
// This program must be compiled with the -RT (Generate RTTI) option.
#include <iostream.h>
#include <typeinfo.h>
class Base1
{
// In order for the RTTI mechanism to function correctly,
// a base class must be polymorphic.
virtual void f(void) { /* A virtual function makes the class polymorphic */ }
};
class Base2 { };
class Derived : public Base1, public Base2 { };
if ((pd = dynamic_cast<Derived *>(b1)) != 0) {
cout << "The resulting pointer is of type "
<< typeid(pd).name() << endl;
}
else throw Bad_cast();
// Attempt cast across the hierarchy. That is, cast from
// the first base to the most derived class and then back
// to another accessible base.
Base2 *b2;
if ((b2 = dynamic_cast<Base2 *>(b1)) != 0) {
cout << "The resulting pointer is of type "