C++/C++ static, reinterpert, dynamic cast

static_cast

재윤 2024. 1. 26. 15:55
반응형

static_cast는 언어에서 지원하는 명시적 변환을 수행한다.

 

→ 작은 데이터 타입에서 큰 데이터 타입으로 바꾸기

  • 예를 들어 다음 코드처럼 정수에 대한 나눗셈이 아닌 부동소수점에 대한 나눗셈으로 처리하도록 int를 double로 변환해야 할 때가 있다. 이때 static_cast()를 사용하면 된다.
int i{ 3 };
int j{ 4 };
double result{ static_cast<double>(i) / j };

 

→ 더 큰 데이터 타입에서 더 작은 데이터 타입으로 변환

double pi = 3.141592653589793;
int integerPi = static_cast<int>(pi); // 더 큰 double을 더 작은 int로 형 변환

 

→ 기본 데이터 타입 사이의 형 변환

int intValue = 42;
char charValue = static_cast<char>(intValue); // int를 char로 형 변환

 

→ 제일 중요한 부분은 다운 캐스팅을 사용할 수 있다.

class Base {
public:
    virtual void foo() {}
};

class Derived : public Base {};

Base* basePtr = new Derived();
Derived* derivedPtr = static_cast<Derived*>(basePtr); // Base 포인터를 Derived 포인터로 형 변환

 

그런데

  • 이런 캐스팅에서 객체 범위를 벗어난 영역의 메모리를 덮어쓰는 심각한 문제가 발생할 수 있다.
  • 이것을 해결하기 위해 dynamic_cast를 사용
Base* b{ new Base{} };
Derived* d{ static_cast<Derived*>(b) };

[C++] 캐스팅(Casting)

 

[C++] 캐스팅(Casting)

References Professional C++ https://en.cppreference.com/w/ Contents const_cast() static_cast() reinterpret_cast() dynamic_cast() std::bit_cast() C++에서는 어떤 타입을 다른 타입으로 캐스팅하기 위한, const_cast(), static_cast(), reinterp

junstar92.tistory.com

 

반응형

'C++ > C++ static, reinterpert, dynamic cast' 카테고리의 다른 글

dynamic_cast  (2) 2024.01.26
reinterpret_cast  (0) 2024.01.26