const_cast는 피연산자의 하위 const만을 변경하여 const를 날려 버릴 수 있다.
int main()
{
char str[] = "abcd";
const char* csptr = str;
char* sptr = const_cast<char*>(csptr);
sptr[1] = 'B';
cout << str << endl;
return 0;
}
결과
aBcd
int main()
{
const int i = 1;
const int* cip = &i;
int* ip = const_cast<int*>(cip);
*ip = 2;
cout << *ip << endl;
cout << *cip << endl;
cout << i << endl;
return 0;
}
결과
2
2
1
본래 i가 const이기에 값은 바뀌지 않는다.
'C++ > 기억하고 싶은 거' 카테고리의 다른 글
[C++] 함수의 매개변수에 참조자와 const (0) | 2023.05.31 |
---|---|
[C++] const에 대한 참조자와 포인터 (0) | 2023.05.17 |
[C++] namespace (0) | 2023.05.07 |