C++

Ch10. C++ 캐스팅

javadocq 2024. 1. 22. 13:58
728x90

C언어의 경우에는 소괄호를 이용해 캐스팅을 하곤 했다. 예를 들어 cm라는 실수형 변수를 정수형으로 바꾸고 싶을 때는

cm -> (int)(cm) 이렇게 표시를 하였다. 이거를 명시적 캐스팅이라고 하는데 C++에서는 4가지로 캐스팅을 구현할 수 있게 해놓았다.

 

 

1. 정적 캐스트 (Static Cast):

2. 동적 캐스트 (Dynamic Cast):

3. 상수 캐스트 (Const Cast):

4. 리인터프리트 캐스트 (Reinterpret Cast):

 

위 4가지 캐스팅의 사용 방법은 다음과 같다.

 

(캐스트 종류)<바꾸려는 타입>(바꾸려는 변수)

 

우리가 C언어에서 사용하는 캐스팅과 비슷한 것은 정적 캐스트이다. 그래서 C언어에서 적용이 되던 캐스팅은 다 정적 캐스트로도 가능하다.

 

1. 정적 캐스트 (Static Cast):

정적 캐스트는 가장 일반적으로 사용되는 캐스팅 유형으로 컴파일러가 타입을 변환하는데 사용이 된다.

 

#include <iostream>

int main() {
float cm;
std::cout << "Enter the cm : ";
std::cin >> cm;
std::cout << "float type : " << cm << std::endl;
std::cout << "int type : " << static_cast<int>(cm) << std::endl;
}


다음 예제는 float 타입인 변수를 int 타입으로 바꾸는 예제이다.

 

Enter the cm : 175.12

float type : 175.12

int type : 175

Process exited with status 0

 

2. 동적 캐스트 (Dynamic Cast):

동적 캐스트는 실행 시간에 유효성을 검사하고, 안전한 다운캐스팅을 지원한다. 그리고 다형성을 지원할 때 주로 사용하는 편이다.

 

#include <iostream>

class Bottom {
public:
virtual ~Bottom() {}
};

class Top : public Bottom{};

int main() {
Bottom* bottomptr = new Top();
Top* topptr = dynamic_cast<Top*>(bottomptr);
if(topptr != nullptr) {
std::cout << "complete" << std::endl;
}
else {
std::cout << "no complete" << std::endl;
}
}


 

complete

Process exited with status 0

 

 

3. 상수 캐스트 (Const Cast):

상수 캐스트는 포인터 또는 참조의 상수성을 제거하거나 추가한다. 

 

#include <iostream>

int main() {
const int number = 97;
 
int* numberptr = const_cast<int*>(&number);

*numberptr = 50;
 
std::cout << "number : " << *numberptr << std::endl;

}

 

number : 50

Process exited with status 0

 

4. 리인터프리트 캐스트 (Reinterpret Cast):

리인터프리트 캐스트는 비트 수준에서 메모리를 다른 타입으로 해석한다.

 

int intValue = 42;

float floatValue = reinterpret_cast<float>(intValue);