//----------------------------------------------------------- // // cast.cpp // // A program to illustrate different forms of casting in C++ // // Simon Parsons // // 8th February 2010 // //----------------------------------------------------------- // // Libraries etc. #include using namespace std; //----------------------------------------------------------- // // showSuit // void showSuit( int card ) { enum suits { diamonds, clubs, hearts, spades } suit; // Here we use cast to convert an integer into a "suit" suit = static_cast( card / 13 ); // Since an enum is basically an integer, we can use it in // a switch. switch( suit ) { case diamonds: cout << "diamonds"; break; case clubs: cout << "clubs"; break; case hearts: cout << "hearts"; break; case spades: cout << "spades"; break; } cout << endl; } //----------------------------------------------------------- // // main // int main() { double d = 65.6; // Casting in the old-fashioned way int i = (double)d; // truncates char c = (char)i; // uses ascii table cout << "d=" << d << endl; cout << "i=" << i << endl; cout << "c=" << c << endl; // Casting the correct new way int j = static_cast(d); cout << "j=" << j << endl; // Casting a modifiable version of a const. const int k = 75; int n = const_cast(k); cout << "k=" << k << endl; cout << "n=" << n << endl; showSuit( 49 ); } // // End of main // //-----------------------------------------------------------