The static_cast operator converts expression to type-id type, but there is no runtime type check to ensure the safety of the conversion.
① Used to convert pointers or references between base classes (parent classes) and derived classes (subclasses) in the class hierarchy.
It is safe to perform upstream conversion (convert a pointer or reference of a derived class into a base class representation);
When performing downconversion (convert a pointer or reference from a base class to a derived class representation), because there is no Dynamic type checking, so it is unsafe.
From: http://baike.baidu.com/link?u...
I would like to ask, what does the bold part mean? What does unsafe mean?
For example, there is a parent class
A
, which derives two subclassesB
andC
. There is aA
class pointer or referencea
pointing to aB
class object b. In this case, usestatic_cast
performs downward conversion and can convert it into an object (pointer or reference) of classC
. At this time, it will be unsafe because some member functions/variables of classC
are not compatible with objects of classB
Be applicable.Simply put, you can use
static_cast
to convert objects of different subclasses of the same parent class to each other, resulting in type errors.For example: