C++

[C++] 캐스팅(Casting)

Airhood 2024. 10. 16. 00:48

캐스팅이란?

캐스팅이란 한 데이터 타입을 다른 데이터 타입으로 변환하는 과정을 말한다.

 

C++에서 지원하는 캐스팅의 종류

- static_cast

- dynamic_cast

- const_cast

- reinterpret_cast

 

 

1. static_cast

논리적으로 변환 가능한 타입을 변환하는 캐스팅으로 컴파일 타임에 타입 검사를 수행한다.

 

static_cast<new_type>(expression)

 

int a = 10;
float a_1 = static_cast<float>(a);
double a_2 = static_cast<double>(a);

float b = 5.7f;
int b_1 = static_cast<int>(b);
double b_2 = static_cast<double>(b);

double c = 2.74;
int c_1 = static_cast<int>(c);
float c_2 = static_cast<float>(c);

 

가능한 경우

- 실수와 정수, 열거형과 정수 사이의 변환 등

- Upcasting 하는 경우 (자식 클래스에서 부모 클래스, static_cast<부모 클래스>(자식 클래스))

 

가능하지 않은 경우

- 값과 포인터 사이의 변환

- Downcasting 하는 경우 (부모 클래스에서 자식 클래스, static_cast<자식 클래스>(부모 클래스))

 

 

2. dynamic_cast

같은 상속 계층에 속한 타입끼리 변환하는 캐스팅으로 런타임에 타입을 검사한다.

 

런타임에 내부 객체의 타입 정보를 검사하는데, 이때 캐스팅이 적합하지 않다고 판단되면 포인터의 경우 nullptr을 리턴하고 값의 경우 std::bad_cast 예외를 발생시킨다.

 

dynamic_cast를 사용하기 위해서는 하나 이상의 가상함수를 가져야 한다.

 

dynamic_cast<new_type>(expression)

 

class Base {
public:
    virtual ~Base() = default;
};

class Derived : public Base {
public:
    ~Derived() = default;
};

int main() {
    Base* base = new Derived();
    Derived* derived = dynamic_cast<Derived*>(base);
}

 

3. const_cast

포인터(pointer) 또는 참조형(reference)의 상수성(const)을 제거하거나 추가할 때 사용되는 캐스팅이다.

 

함수 포인터에는 사용할 수 없다.

 

const_cast<new_type>(expression)

 

const int a = 10;
int* b = const_cast<int*>(&a);

int a = 10;
const int& ref = a;
int& b = const_cast<int&>(a);

 

4. reinterpret_cast

임의의 포인터 타입끼리 변환하는 캐스팅이다.

 

포인터를 정수형 타입으로 변환하거나 반대로 변환하는 것도 가능하지만, 새로운 타입의 크기가 이전 타입의 크기보다 같거나 커야 한다.

 

reinterpret_cast<new_type>(expression)

 

int a = 10;
int* b = &a;
char* c = reinterpret_cast<char*>(b);

int& d = a;
char& e = reinterpret_cast<char&>(d);