본문 바로가기

C++/C, C++, STL

4가지 유형의 형변환(캐스트, Cast) 연산자

이 문서의 내용

    캐스트(Cast) 연산자

    C++에서는 전용 캐스트 연산자를 제공합니다. 이 연산자들은 C 언어에서 캐스팅 방식의 모호함과 위험성을 제거하기 위한 목적으로 등장하였습니다.

    const_castreinterpret_cast 연산자는 C 언어에서의 캐스팅 방식의 오점을 여전히 갖고 있기 때문에 최후의 방법입니다.

    const_cast 연산자

    이 연산자의 기본 구문은 다음과 같습니다.

    const_cast <type-id> (expression)

    이름에서 알 수 있듯이 상수 타입 간 캐스팅에서 사용되며 다른 상수로의 형 변환은 불가능합니다.

    class CTest
    {
    private:
    	int v;
    
    public:
    	CTest(int v) 
    	{ 
    		(this) -> v = v; 
    	};
            
    	void printValue()
    	{
    		std::cout << v << std::endl;
    		const_cast<CTest*>(this)->v--;
    		std::cout << v << std::endl;
    	}
    };
    
    int main()
    {
    	CTest test = CTest(100);
    	test.printValue();
    	return 0;
    }
    코드 비고
    Line 15 const_cast<CTest*>(this) this 포인터의 데이터 형식은 const CTest*입니다. 이를 CTest*로 변환하여 필드를 직접 수정합니다.

    static_cast 연사자

    이 연산자의 기본 구문은 다음과 같습니다.

    static_cast <type-id> ( expression )

    논리적으로 형 변환이 가능한 경우에만 허용되며 그렇지 않은 경우는 방지합니다.

    • 실수 <-> 정수 간의 형 변환 가능
    • 클래스 포인터 <-> 클래스 간의 형 변환 가능
    • 부모 클래스 포인터 -> 자식 클래스 포인터의 형 변환 가능 등
    #include <iostream>
    
    class Parent
    {
        
    };
    
    class Child: public Parent
    {
    public:
    	void helloWorld()
    	{
    		std::cout << "helloWorld!" << std::endl;
    	};
    };
    
    int main()
    {
    	Parent* p = new Parent();
    	Child* c = static_cast<Child*>(p);
    	(*c).helloWorld();
    	return 0;
    }

    dynamic_cast 연산자

    이 연산자의 기본 구문은 다음과 같습니다.

    dynamic_cast < type-id > ( expression )

    실행시간 타입정보(RTTI, Runtime Type Information)가 필요하며 다형성(Polymorphic)을 따르고 있어야합니다.

    • 포인터 <-> 포인터 간의 형 변환 가능
    • 참조 타입 <-> 참조 타입 간의 형 변환 가능
    #include <iostream>
    
    class Parent
    {
    public:
    	virtual ~Parent() { };
    };
    
    class Child: public Parent
    {
    public:
    	void helloWorld()
    	{
    		std::cout << "helloWorld!" << std::endl;
    	};
    };
    
    int main()
    {
    	Parent* p = new Parent();
    	Child* c = dynamic_cast<Child*>(p);
    	(*c).helloWorld();
    	return 0;
    }

    reinterpret_cast 연산자

    이 연산자의 기본 구문은 다음과 같습니다.

    reinterpret_cast < type-id > ( expression )

    임의의 포인터 타입 간의 형 변환이 가능하며 가장 위험한 캐스팅 방식입니다.

    int main()
    {
    	int n = 1000;
    
    	int* np = reinterpret_cast<int*>(n);
    	char* cp = reinterpret_cast<char*>(np);
    	
    	return 0;
    }
    코드 비고
    Line 5 reinterpret_cast<int*>(n) int 타입int 포인터 타입으로 캐스팅합니다.
    Line 6 reinterpret_cast<char*>(np) int 포인터 타입char 포인터 타입으로 캐스팅합니다.