Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- npm
- Node
- Chunk
- 정규표현식
- Regular expression
- git
- Spring Batch
- spring
- upgrade
- update
- Effective Java 3/e
- spring cloud
- REACTJS
- expire_logs_days
- REACT
- MySQL
- java
- log4j2
- 퀵소트
- migration
- Effective Java
- mysql 5.5
- log_bin
- JavaScript
- eslint
- Webpack
- nodejs
- current_date
- Express
- regex
Archives
- Today
- Total
내 세상
[C++] C++스타일의 캐스팅 본문
728x90
반응형
C++ 스타일의 캐스팅
- static_cast
- 표준 타입을 값으로 캐스팅
- 상속 관계 타입의 캐스팅
- lvalue => rvalue 변환
- void* => 다른 타입으로 변환
- reinterpret_cast
- 메모리의 재해석
- 서로 다른 타입의 주소 변환
- 정수 <=> 포인터 사이 변환
- const_cast
- 동일 타입의 const 속성을 제거하는 캐스팅
<< static_cast >>
#include <cstdio>
#include <cstdlib>
// static_cast : 가장 일반적인 용도
// 1. 표준 타입을 값으로 캐스팅
// 2. 상속 관계 타입의 캐스팅
// 3. lvalue => rvalue 변환
// 4. void* => 다른 타입으로 변환
int main()
{
double d = 3.4;
int n1 = d; // ok
int n2 = static_cast<int>(d); // square<int>(3);
int* p1 = static_cast<int*>(&d); // error. 서로 다른 타입의
// 주소를 캐스팅할 수 없다.
int* p2 = static_cast<int*>(malloc(100)); // void* => int*
// ok....
const int c = 10;
int * p3 = static_cast<int*>(&c); // const int * => int *
// error
}
<< reinterpret_cast >>
#include <iostream>
// reinterpret_cast : 메모리의 재해석
// 1. 서로다른 타입의 주소 변환
// 2. 정수 <=> 포인터 사이 변환
int main()
{
int n = 0x11223344;
//char* p5 = static_cast<char*>(&n);
//std::cout << *p5 << std::endl;
char* p5 = reinterpret_cast<char*>(&n);
std::cout << *p5 << std::endl; // 44 나온다.
double d = 3.4;
int* p = reinterpret_cast<int*>(&d); // ok
std::cout << p << std::endl; // 주소
std::cout << *p << std::endl; // 값 ... 전혀 다른 값이 출력
// 메모리에는 float point 방식으로 저장
// 읽을때는 int로 해석 => 완전히 잘못된 값
// 메모리에는 "3.4"가
// 단 아래와 같은 표기는 위험하므로 조심해서 사용
// *p = 3.4;
// int n = reinterpret_cast<int>(d); // error. 값 캐스팅은
// 할 수 없음.
// 정수 <=> 포인터 간의 변환에 사용
int *p2 = reinterpret_cast<int*>(1000); // ok
// 서로 다른 타입이지만, 상수성을 제거하는 것.
const int c = 10;
//int* p3 = reinterpret_cast<int*>(&c); // error. const 속성 제거 할 수 없음. 안됨.
}
<< const_cast >>
// const_cast : 동일 타입의 const 속성을 제거하는 캐스팅
int main()
{
const int c = 10;
int * p = const_cast<int*>(&c); // ok
// c의 주소를 char* p2에 담아 보세요
// 단, c++ 캐스팅 사용해서
/*
char* p2 = reinterpret_cast<char*>(&c);
*/
char* p2 = reinterpret_cast<char*>(const_cast<int*>(&c));
char* p3 = (char*)&c; // c 스타일
}
728x90
반응형
'Language > C/C++' 카테고리의 다른 글
[C++] 동적 메모리/ 레퍼런스 (0) | 2020.01.02 |
---|---|
[C++] nullptr (0) | 2020.01.02 |
[C++] C++11/C++17 에서의 반복문/제어문 (0) | 2020.01.02 |
[C++] 함수 (0) | 2020.01.02 |
[C++] 표준입출력, 변수 선언 (0) | 2020.01.02 |