Created
July 28, 2010 23:34
-
-
Save h1mesuke/496741 to your computer and use it in GitHub Desktop.
C++ - Sample usages of xxx_cast()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Base { | |
virtual void f() {}; | |
}; | |
class Derived: public Base { | |
}; | |
int main(int argc, const char *argv[]) | |
{ | |
// dynamic_cast | |
{ | |
Base *bp, b; | |
Derived *dp, d; | |
cout << endl; | |
cout << "== dynamic_cast" << endl; | |
bp = &b; | |
if (dp = dynamic_cast<Derived *> (bp)) { | |
cout << "cast bp(&b) to dp: success" << endl; | |
} else { | |
cout << "cast bp(&b) to dp: failure" << endl; | |
} | |
bp = &d; | |
if (dp = dynamic_cast<Derived *> (bp)) { | |
cout << "cast bp(&d) to dp: success" << endl; | |
} else { | |
cout << "cast bp(&d) to dp: failure" << endl; | |
} | |
} | |
// const_cast | |
{ | |
int i = 10; | |
const int *p = &i; | |
int *q; | |
cout << endl; | |
cout << "== const_cast" << endl; | |
//*p = 20; | |
//-> error | |
q = const_cast<int *> (p); | |
*q = 20; | |
cout << "*p = " << *p << endl; | |
} | |
// reinterpret_cast | |
{ | |
int i; | |
char *p = "hello"; | |
cout << endl; | |
cout << "== dynamic_cast" << endl; | |
i = reinterpret_cast<int> (p); | |
//-> warning: deprecated conversion from string constant to ‘char*’ | |
cout << "i = " << i << endl; | |
} | |
// static_cast | |
{ | |
float f = 3.14; | |
int i; | |
cout << endl; | |
cout << "== static_cast" << endl; | |
i = static_cast<int> (f); | |
cout << "i = " << i << endl; | |
} | |
return 0; | |
} | |
// vim: filetype=cpp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment