There are mainly four types of cast operators in standard C + +:
Const_cast,reinterpret_cast,static_cast,dynamic_cast and so on.
1) static_cast<t*> (a)
Converting address A to type t,t and a must be a pointer, reference, arithmetic type, or enumeration type.
Expression static_cast<t*> (a), the value of a is converted to the type T specified in the template. During run-time conversion, no type checking is performed to ensure the security of the conversion.
Example:
class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // 不安全, pb可能只是B的指针
B* pb2 = static_cast<B*>(pd); // 安全的
...
}
class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // 不安全, pb可能只是B的指针
B* pb2 = static_cast<B*>(pd); // 安全的
...
}
class B { ... };
class D : public B { ... };
void f(B* pb, D* pd)
{
D* pd2 = static_cast<D*>(pb); // 不安全, pb可能只是B的指针
B* pb2 = static_cast<B*>(pd); // 安全的
...
}
2) dynamic_cast<t*> (a)
completes the promotion in the class hierarchy. T must be a pointer, reference, or a pointer of no type. A must be an expression that determines a pointer or reference.
An expression dynamic_cast<t*> (a) converts a value to an object pointer of type T. If the type T is not a base type of a, the operation returns a null pointer.
Example:
class A { ... };
class B { ... };
void f()
{
A* pa = new A;
B* pb = new B;
void* pv = dynamic_cast<A*>(pa);
// pv 现在指向了一个类型为A的对象
...
pv = dynamic_cast<B*>(pb);
// pv 现在指向了一个类型为B的对象
}