cpp_Explicit_Casting - 8BitsCoding/RobotMentor GitHub Wiki
int i = 9;
float f = static_cast<float>(i);
// ์ ์ฌํ ๋ค๋ฅธํ์ผ๋ก ๋ณํ
dog d1 = static_cast<dog>(string("Bob"));
// dog๋ด์ string์ผ๋ก ํ๋ณํ
dog* pd = static_cast<dog*>(new yellowdog());
// ๊ด๋ จ๋ ์ค๋ธ์ ํธ๋ก ๋ค์ด/์
์บ์คํ
dog* pd = new yellowdog();
yellowdog py = dynamic_cast<yellowdog*>(pd);
// ๊ด๋ จ๋ ์ค๋ธ์ ํธ๋ก ๋ค์ด/์
์บ์คํ
// ๋ง์ฝ ์คํจ์ ๋ฐํ์์์ NULL๋ฐํ
const char* str = "Hello, world";
char* modifiable = const_cast<char*>(str);
// ๊ฐ์ ํ์
์์๋ง ๊ฐ๋ฅ
// ์บ์คํ
ํ const์ ๊ฑฐ ๊ฐ๋ฅ
long p = 51110980;
dog* dd = reinterpret_cast<dog*>(p);
// ๊ฐ์ ํ๋ณํ
์๋ ์ฝ๋์ ๋ฌธ์ ์ ์ด ๋ญ๊น?
class dog {
public:
virtual ~dog() {}
};
class yellowdog : public dog {
private:
int age;
public:
void bark() { cout << "woof. " << endl; }
};
int main() {
dog* pd = new dog();
//...
yellowdog* py = dynamic_cast<yellowdog*>(pd);
py->bark();
cout << "py = " << py << endl;
cout << "pd = " << pd << endl;
}
์ฐ์ ์ถ๋ ฅ์ ๋ค์๊ณผ ๊ฐ์ด ๋์จ๋ค.
woof.
py = 0
pd = 57873400
๋ฌธ์ ์ ์ ๋ค์๊ณผ ๊ฐ๋ค.
yellowdog* py = dynamic_cast<yellowdog*>(pd);
๋ชจ๋ yellowdog๋ dog๋ผ ํ ์ ์์ง๋ง ๋ชจ๋ dog๋ฅผ yellowdog๋ผ ํ ์ ์๋ค.
๋ฐ๋ผ์ dynamic_cast์์ 0์ด ๋ฆฌํด์ด ๋๋ค.(Runtime)
๊ทธ๋ผ? woof๊ฐ ์ถ๋ ฅ๋ ์ด์ ๋?
barkํจ์์์ ๋ฐ๋ก yellowdog์ ๋ฐ์ดํฐ์ ์ ๊ทผ์ ํ์ง ์์๊ธฐ์ ๊ฐ๋ฅํ๋ค ๋ง์ฝ์ bark์ฝ๋๊ฐ ๋ค์๊ณผ ๊ฐ์๋ค๋ฉด ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
class yellowdog : public dog {
private:
int age;
public:
void bark() { cout << "woof. " << age << endl; }
};
class dog {
public:
virtual ~dog() {}
};
class yellowdog : public dog {
private:
int age;
public:
void bark() { cout << "woof. " << endl; }
};
int main() {
dog* pd = new dog();
//...
//yellowdog* py = static_cast<yellowdog*>(pd);
// static_cast์ด์ฉ?? -> ๋ ์ํ
yellowdog* py = dynamic_cast<yellowdog*>(pd);
if(py)
py->bark();
// ์กฐ๊ฑด๋ฌธ์ ๋ฃ์ด์ ์ฌ์ฉํ์
cout << "py = " << py << endl;
cout << "pd = " << pd << endl;
}
class dog {
public:
std:string m_name;
dog() : m_name("Bob") {}
void bark() const {
const_cast<dog*>(this)->m_name = "Henry";
}
};