이전 포스팅에서 static에 대해 알아보았다. 이번에는 const와 final에 대해 알아보자.
3을 3이 아닌 다른 값으로 바꿀 수 없듯이 const 메소드는 해당 변수를 더 이상 값 변경이 불가능한 상수로 만든다.
💡 코드를 짜는 중에, 고정되어 있어야 할 값을 const로 선언함으로써 그 의도를 분명히 할 수 있다.
const int a = 1;
a = 2; // error
따라서, const 변수는 선언할 때에 반드시 초기화를 해주어야 한다. 특히 class field에 const 멤버를 사용할 경우, 멤버 초기화 리스트를 사용하지 않으면 안 된다.
class right_class {
const int a;
myclass() : a(1); // ok. a=1
};
class wrong_class {
const int a;
myclass() {a = 1;} // compile error
}
const 포인터를 사용할 때에는 const의 위치에 따라 그 의미가 달라진다.
int a = 1;
const int *ptr = &a;
이 때는 const int가 *ptr을 가리킨다. 따라서 *ptr (포인터가 가리키는 값)은 바꿀 수 없지만 ptr (주소값)은 바꿀 수 있다.
int a = 1, b = 10;
const int *ptr = &a;
// *ptr = 2; // compile error
a = 2; // ok
ptr = &b; // ok
cout << *ptr << "," << a << endl; // result: 10,2
int a = 1;
int* const ptr = &a;
이 때는 const가 ptr을 가리킨다. ptr에는 주소값이 담기기 때문에, ptr의 주소값은 변경이 불가하지만, *ptr (포인터가 가리키는 값)은 변경할 수 있다.
int a = 1, b = 10;
int* const ptr = &a;
*ptr = 2; // ok
// ptr = &b; // compile error
cout << *ptr << "," << a << endl; // result: 2,2
int a = 1, b = 10;
const int* const ptr = &a;
// *ptr = 2; // compile error
// ptr = &b; // compile error
이 때는 1)과 2)의 경우가 모두 적용되므로 어떠한 변경도 불가능한 '상수' 포인터가 된다.
Reference
C/C++ const 개념 한번에 이해하기
C++ const 이해하기
https://melonplaymods.com/2023/06/10/human-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/bar-for-melon-playground-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/kamen-rider-geats-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/flower-tail-pigeon-machinery-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/capsules-pills-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/automatic-sterilizer-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/missile-launching-pad-and-flying-sparrow-missile-m-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/secret-laboratory-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/melon-five-story-building-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/russian-and-ukrainian-flags-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/multiple-ships-flags-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/red-dead-redemption-arthur-morgan-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/grabpack-and-toys-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/armored-car-mod-for-melon-playground-2/
https://melonplaymods.com/2023/06/11/npc-ant-man-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/gang-bucciarati-from-anime-jojo-season-5-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/underworld-mod-for-melon-playground/
https://melonplaymods.com/2023/06/10/alan-becker-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/basketball-box-mod-for-melon-playground/
https://melonplaymods.com/2023/06/11/robot-mod-for-melon-playground-2/