#include #include using namespace std; int main() { // Part 1: Static Cast. // Change a value of one datatype to // a value of a different type. int x[] = {4, 2, 7, 5, 9, 4}; int sum = 0, count = 0, i; double ave; for(i = 0; i < 6; i++) { sum += x[i]; count++; } ave = static_cast(sum) / count; cout << "The average is " << ave << endl; // Part 2: Reinterpret Cast. // Convert a pointer of one datatype to a // pointer of a different datatype. This // cast only makes sense in unusual // circumstances. float f = 4.756F; unsigned char *p; p = reinterpret_cast(&f); cout << hex << setfill('0'); for(i = 0; i < sizeof(float); i++) cout << setw(2) << static_cast(*(p + i)); cout << endl; cout << dec; // Part 3: Const Cast. // Used to cast away "const-ness" in // a pointer. const int u = 5, *q = &u; int *r; r = const_cast(q); *r += 7; cout << u << " " << *q << " " << *r << endl; cout << &u << " " << q << " " << r << endl; // Part 4: Dynamic Cast // Used to cast to other types in // an inheritance hierarchy. // To be discussed later. return EXIT_SUCCESS; } // Output: // The average is 5.16667 // 27319840 // 5 12 12 // 0012FF48 0012FF48 0012FF48