관리 메뉴

ComputerVision Jack

[C++프로그래밍 Chapter16] 본문

Programming Language/C++ Programming

[C++프로그래밍 Chapter16]

JackYoon 2020. 2. 7. 13:56
반응형

[형 변환 연산]

C++의 4개의 형변환 연산자

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast

dynamic_cast

상속 관계에서의 안전한 형 변환

dynamic_cast<T>(expr)

상속 관계에 놓여 있는 두 클래스 사이에서 유도 클래스의 포인터 및 참조형 데이터를

기초 클래스의 포인터 및 참조형 데이터 형 변환하는 경우

 

Two * tptr = new Two(10, 20);

One * optr = dynamic_cast<One*>(tptr);

 

static_cast

A 타입에서 B타입으로.

static_cast<T>(expr)

유도 클래스의 포인터 및 참조형 데이터를 기초 클래스의 포인터 및 참조형 데이터로 뿐만 아니라

기초 클래스의 포인터 및 참조형 데이터도 유도 클래스의 포인터 및 참조형 데이터로 형 변환시킨다.

하지만 책임은 프로그래머에게 달려있다.

 

One *optr = new Two(10, 20);

Two * tptr = static_cast<One*>(optr);

 

const_cast

const의 성향을 삭제해라.

const_cast<T>(expr)

참조자의 const성향을 제거하는 형변환 목적으로 사용된다.

 

const char * name ="Hong";

ShowString(const_cast<char*>(name));

 

reinterpret_cast

상관없는 자료형으로 형 변환

reinterpret_cast<T>(expr)

전혀 상관없는 자료형으로 형 변환에 사용된다. 서로 상관 없는 Sample, One 클래스에 대하여

 

Simple * sp = new Simple;

One * one = reinterpret_cast<One*>(sp);

포인터를 대상으로 하는, 포인터와 관련이 있는 모든 유형의 형변환을 사용한다.

 

 

반응형

'Programming Language > C++ Programming' 카테고리의 다른 글

[C++프로그래밍 Chapter15]  (0) 2020.02.06
[C++프로그래밍 Chapter14]  (0) 2020.02.05
[C++프로그래밍 Chapter13]  (0) 2020.02.04
[C++프로그래밍 Chapter12]  (0) 2020.02.03
[C++프로그래밍 Chapter11]  (0) 2020.02.01
Comments