Created
January 29, 2018 14:34
-
-
Save fortheday/f1d755a09d575d03c372d24c19c8acee to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class CBase { | |
virtual void f() {} | |
}; | |
class CDerieve : public CBase { | |
virtual void f() override {} | |
}; | |
void CastTest() | |
{ | |
// dynamic cast with reference | |
{ | |
CBase b; | |
CDerieve &rD = dynamic_cast<CDerieve &>(b); // throw std::bad_cast | |
} | |
// const_cast는 떼거나 붙이거나 둘 다 가능. | |
// C cast vs static_cast | |
{ | |
unsigned char c; | |
c = (unsigned char)int(256); | |
std::cout << (int)c << std::endl; // 0 | |
c = static_cast<unsigned char>(int(257)); | |
std::cout << (int)c << std::endl; // 1 | |
c = (unsigned char)float(1.5f); | |
std::cout << (int)c << std::endl; // 1 | |
c = static_cast<unsigned char>(float(1.6f)); | |
std::cout << (int)c << std::endl; // 1 | |
c = reinterpret_cast<unsigned char>(int(128)); // COMPILE ERROR | |
} | |
// reinterpret usage 1 | |
{ | |
int *pInt = nullptr; | |
char *pChar = nullptr; | |
pInt = (int *)pChar; | |
pInt = reinterpret_cast<int *>(pChar); | |
pInt = static_cast<int *>(pChar); // COMPILE ERROR | |
pChar = (char *)pInt; | |
pChar = reinterpret_cast<char *>(pInt); | |
pChar = static_cast<char *>(pInt); // COMPILE ERROR | |
} | |
// reinterpret usage 2 | |
{ | |
short s = 2; | |
char *p; | |
p = (char *)s; | |
p = reinterpret_cast<char*>(s); | |
p = static_cast<char*>(s); // COMPILE ERROR | |
s = (short)p; | |
s = reinterpret_cast<short>(p); | |
s = static_cast<short>(p); // COMMPILE ERROR | |
std::cout << s << std::endl; // 2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment