초안 : GGWABaeGi @김민수

2024년 6월 14일 오전 12:00 (GMT+9)

C++의 캐스팅 개념

int -> char 의 경우도 마찬가지로 상위 3바이트를 버리게 된다.

포인터의 명시적 표시의 이유? 예를들어 int*의 경우 int가 4byte 이기에 최하위 비트 기준 4byte 만큼의 데이터를 가리킬 수 있음을 뜻한다.

static_cast, dynamic_cast, reinterpret_cast, const_cast

캐스팅

#include <iostream>

class Animal {
public:
    virtual void sound() = 0;
};

class Dog : public Animal {
public:
    void sound() { std::cout << "Woof!" << std::endl; }
};

int main() {
    // Static Cast Example
    Animal* animalPtr = new Dog();
    Dog* dogPtr = static_cast<Dog*>(animalPtr);
    dogPtr->sound();  // Output: Woof!

    /*Dynamic Cast Example*/ 
    // This will throw an exception at runtime!
    Animal* animal2Ptr = new Cat();
    if (Dog* dog2Ptr = dynamic_cast<Dog*>(animal2Ptr)) {
        dog2Ptr->sound();
    } else {
        std::cout << "Not a Dog!" << std::endl;
    }
    
    /*Reinterpret Cast Example*/ 
    Animal* animalPtr = new Dog();
    Dog* dogPtr = reinterpret_cast<Dog*>(animalPtr);
    dogPtr->sound();  // Output: Woof!

		/*Reinterpret Cast Example 2 (Non exsist)*/
    Animal* animalPtr = new Dog();
    //will not throw an exception at runtime but cause error maybe
    Tiger* tigerPtr = reinterpret_cast<Tiger*>(animalPtr);
    tigerPtr->sound();  // error

		/*const cast*/
		//스택영역에 저장된 const로 readonly 제한 영역이 아님.
		const int a = 3;
		const int* pa = &a;
		int* paa = const_cast<int*>(pa);
		*paa = 6;
	
		// 저장된 리터럴이 readonly 영역이므로 쓰기 제한이 걸려버림.
		const char* c = "gfg";
		char* d = const_cast<char*>(c);
		*d = 'c'; // error! 쓰기 위반

    return 0;
}

한줄 요악