cpp_Explicit_Casting - 8BitsCoding/RobotMentor GitHub Wiki

Explicit

static_cast

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());
// ๊ด€๋ จ๋œ ์˜ค๋ธŒ์ ํŠธ๋กœ ๋‹ค์šด/์—… ์บ์ŠคํŒ…

dynamic_cast

dog* pd = new yellowdog();
yellowdog py = dynamic_cast<yellowdog*>(pd);
// ๊ด€๋ จ๋œ ์˜ค๋ธŒ์ ํŠธ๋กœ ๋‹ค์šด/์—… ์บ์ŠคํŒ…
// ๋งŒ์•ฝ ์‹คํŒจ์‹œ ๋Ÿฐํƒ€์ž„์—์„œ NULL๋ฐ˜ํ™˜

const_cast

const char* str = "Hello, world";
char* modifiable = const_cast<char*>(str);
// ๊ฐ™์€ ํƒ€์ž…์—์„œ๋งŒ ๊ฐ€๋Šฅ
// ์บ์ŠคํŒ… ํ›„ const์ œ๊ฑฐ ๊ฐ€๋Šฅ

reinterpret_cast

long p = 51110980;
dog* dd = reinterpret_cast<dog*>(p);
// ๊ฐ•์ œ ํ˜•๋ณ€ํ™˜

์ถ”๊ฐ€> Example with dynamic_cast

์•„๋ž˜ ์ฝ”๋“œ์˜ ๋ฌธ์ œ์ ์ด ๋ญ˜๊นŒ?

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;
}

const๊ฐ€ ์„ ์–ธ๋œ ํ•จ์ˆ˜์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด?

class dog {
public:
    std:string m_name;
    dog() : m_name("Bob") {}

    void bark() const {
        const_cast<dog*>(this)->m_name = "Henry";
    }
};

์œ ํˆฌ๋ถ€
์œ ํˆฌ๋ถ€2

โš ๏ธ **GitHub.com Fallback** โš ๏ธ