(
target-type)
value
int i = (int) 1.0;
conversion-kind<target-type>(source-value)
.
int i = static_cast<int>(1.0);
This is way ugly syntax, on purpose probably.
const
and volatile
.
*
and void *
, int
and
double
, and so on.
static_cast<
target-type>(val)
val
.
int i = static_cast<int>('c'); char c = static_cast<char>(1024); int i = static_cast<int>(pi + 0.5);
You need to understand how the values are changed.
const
or volatile
modifiers.
volatile
is a hint to control compiler optimization.
const_cast<
target-type>(val)
val
's type must be const T *
, const T &
, or
const T
.
val
's type is const T *
,T *
.
val
has type const T
,T &
.
val
.
void t(const int * ip, const string & sr, const vector<int> iv) { *(const_cast<int *>(ip)) = 3; const_cast<string &>(sr) = "hello"; (const_cast<vector<int> &>(iv))[0] = 0; }
These kinds of constant casts are almost always bad.
bool C::find(int value) const { const_cast<C *>(this)->find_count++; return fnd(value); }
reinterpret_cast<
target-type>(val)
T2 * t2p = &t2_value; T1 * t1p = reinterpret_cast<T1 *>(t2p); t2p_copy = reinterpret_cast<T2 *>(t1p); // Always true. assert(t2p_copy == t2p);
// wrong, a static cast. int i = reinterpret_cast<int>(1.0); // wrong, a reinterpret cast. char * cp = static_cast<char *>(ip);
dynamic_cast<
target-type>(val)
val
should be a pointer to a class.
val
isn't the target type, the cast returns 0.
C
, casting values of other types to or from values
of type C
is often useful.
C
is big_int
.
big_int bi = "1000000000000000000000000000";
string msg = string("128! = ") + bi;
C::C(const T & tval)
big_int::big_int(const string & str) { ... } big_int bi("100000000000000000000000000");
bi = "10";
"10"
gets converted to a string, which gets converted to a big int, which
gets assigned by bi
.
explicit
keyword can prevent these problems.
explicit C::C(const T & tval);
explicit big_int::big_int(const string & str) { ... } big_int bi("10"); // Counts as explicit. bi = "20"; // Wrong - no explicit call. bi = big_int("30"); // Ok - explicit call.
T
, define a class
operator that casts to T
.
C::operator
target-type ()
big_int::operator string () { ... }
cout << static_cast<string>(bi) << "\n";
explicit
.
string big_int::get_string(void) const { return ...; } cout << bi.get_string() << "\n";
This page last modified on 9 April 2002.