C++ type casting
Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?
Until a few days ago, I've always used C style type casting in C++ because it seemed to work good. I recently found out that using C in C++ is very bad..
I've never really used C++ casting before, so I'm wondering if someone could tell me (in their own words preferably) what the difference between static_cast, reinterpret_cast and const_cast are?
const_cast I know removes a "const" from something, but I'm not sure what the difference between them all is, and what one I need to use in different situations.
To say "C casting is bad" is an extremity that by itself is about as bad as using C-style casts all the time.
The areas where "new" C++ style casts should be used are: hierarchical casts (upcasts, downcasts, crosscasts), const-correctness casts and reinterpretation casts. For arithmetical casts C-style casts work perfectly fine and pose no danger, which is why they can safely be used in C++ code. In fact, I would actually recommend using specifically C-style casts as arithmetical casts - just to make arithmetical casts to look different from other cast types.
static_cast<TYPE>(e-of-TYPE2)
is a safe cast. It means that there is a convert from TYPE2 to TYPE1.
reinterpret_cast
is close to a C cast in that it allows pretty much any conversion (with some limitations). The compiler expects you to know the type conversion is correct.
One thing that neither static_cast
nor reinterpret_cast
are allowed to do is remove a const. IE if you have a const char *
and need to cast it to a char *
, neither static_cast
nor reinterpret_cast
will allow that. Instead, const_cast
is your friend; const_cast
is used for removing a const modifier from a type.
上一篇: 像C vs C类似的强制转换?
下一篇: C ++类型转换