이 글에서는 다양한 기능을 const 키워드 에서 발견되는 것 C++ 논의된다. 언제든지 const 키워드 모든 메소드(), 변수, 포인터 변수 , 클래스의 객체를 사용하면 특정 특정 항목을 방지할 수 있습니다. 객체/메서드()/변수 데이터 항목 값을 수정합니다.
상수 변수:
상수 변수의 선언 및 초기화에는 특정 규칙 세트가 있습니다.
- 그만큼 const 변수 할당 시 초기화되지 않은 상태로 둘 수 없습니다.
- 프로그램의 어느 곳에서도 값을 할당할 수 없습니다.
- 상수 변수 선언 시 상수 변수에 명시적인 값을 제공해야 했습니다.

다음은 위의 개념을 보여주는 C++ 프로그램입니다.
C++ // C++ program to demonstrate the // the above concept #include using namespace std; // Driver Code int main() { // const int x; CTE error // x = 9; CTE error const int y = 10; cout << y; return 0; }> 산출
10>
잘못된 선언으로 인해 발생한 오류 : 명시적인 값을 할당하지 않고 const 변수를 초기화하려고 하면 컴파일 시간 오류(CTE)가 생성됩니다.

포인터 변수가 있는 Const 키워드:
포인터는 const 키워드로 선언할 수 있습니다. 따라서 포인터와 함께 const 키워드를 사용하는 방법에는 다음과 같은 세 가지 방법이 있습니다.
때 포인터 변수는 const 값을 가리킵니다. :
통사론:
const data_type* var_name;>
다음은 위의 개념을 구현하는 C++ 프로그램입니다.
C++ // C++ program to demonstrate the // above concept #include using namespace std; // Driver Code int main() { int x{ 10 }; char y{ 'M' }; const int* i = &x; const char* j = &y; // Value of x and y can be altered, // they are not constant variables x = 9; y = 'A'; // Change of constant values because, // i and j are pointing to const-int // & const-char type value // *i = 6; // *j = 7; cout << *i << ' ' << *j; }> 산출
9 A>
설명: 위의 경우 i와 j는 메모리 위치 const int 유형과 char 유형을 가리키는 두 개의 포인터 변수이지만 이러한 해당 위치에 저장된 값은 위에서 수행한 것처럼 변경될 수 있습니다.
그렇지 않으면 , 그만큼 다음 오류가 나타납니다: const 변수의 값을 수정하려고 하면

const 포인터 변수가 값을 가리킬 때 :
통사론:
영화 123 ~
data_type* const var_name;>
다음은 위의 개념을 보여주는 예입니다.
C++ // C++ program to demonstrate the // above concept #include using namespace std; // Driver Code int main() { // x and z non-const var int x = 5; int z = 6; // y and p non-const var char y = 'A'; char p = 'C'; // const pointer(i) pointing // to the var x's location int* const i = &x; // const pointer(j) pointing // to the var y's location char* const j = &y; // The values that is stored at the memory location can // modified even if we modify it through the pointer // itself No CTE error *i = 10; *j = 'D'; // CTE because pointer variable // is const type so the address // pointed by the pointer variables // can't be changed // i = &z; // j = &p; cout << *i << ' and ' << *j << endl; cout << i << ' and ' << j; return 0; }> 산출
10 and D 0x7ffe21db72b4 and D>
설명: 해당 포인터 변수 i, j에 저장된 값은 수정 가능하지만, x, y의 해당 값이 저장되는 const 포인터 변수가 가리키는 위치는 수정이 불가능합니다.
그렇지 않으면 다음 오류가 나타납니다. 포인터 변수는 const이며 x와 y가 저장된 위치를 가리키며 주소 위치를 변경하려고 하면 오류가 발생합니다.

const 포인터가 const 변수를 가리키는 경우 :
통사론:
const data_type* const var_name;>
다음은 위의 개념을 보여주는 C++ 프로그램입니다.
C++ // C++ program to demonstrate // the above concept #include using namespace std; // Driver code int main() { int x{ 9 }; const int* const i = &x; // *i=10; // The above statement will give CTE // Once Ptr(*i) value is // assigned, later it can't // be modified(Error) char y{ 'A' }; const char* const j = &y; // *j='B'; // The above statement will give CTE // Once Ptr(*j) value is // assigned, later it can't // be modified(Error) cout << *i << ' and ' << *j; return 0; }> 산출
9 and A>
설명: 여기서 const 포인터 변수는 const 변수를 가리킵니다. 따라서 const를 변경할 수 없습니다. 포인터 변수(*P) 그 값이 가리키는 위치에 저장된 값도 아닙니다. 포인터 변수(*P).
이진 검색 트리
그렇지 않으면 다음 오류가 나타납니다. 여기서 포인터 변수와 포인터 변수가 가리키는 위치는 모두 const이므로 둘 중 하나라도 수정되면 다음 오류가 나타납니다.

const 인수 값을 함수의 non-const 매개변수에 전달하면 오류가 발생합니다. : const 인수 값을 함수의 const가 아닌 매개변수에 전달하는 것은 유효하지 않으며 컴파일 타임 오류가 발생합니다.
다음은 위의 개념을 보여주는 C++ 프로그램입니다.
C++ // C++ program to demonstrate // the above concept #include using namespace std; int foo(int* y) { return *y; } // Driver code int main() { int z = 8; const int* x = &z; cout << foo(x); return 0; }> 산출: const 값이 함수의 const가 아닌 인수에 전달된 것처럼 나타나는 컴파일 시간 오류는 다음과 같은 컴파일 시간 오류가 나타납니다.

또한 const 포인터를 전달해도 동일한 메모리 위치를 가리키는 다른 포인터가 생성되므로 오류가 발생하지 않습니다.
C++ //C++ program to demonstrate the above concept #include using namespace std; void printfunc(int* ptr) { cout << 'Value :' << *ptr << endl; cout << 'Address of ptr :' << &ptr << endl; } //Driver Code int main() { int x = 10; int* const i = &x; printfunc(i); cout << 'Address of i :' << &i << endl; }> 산출
Value :10 Address of ptr :0x7ffff0189b48 Address of i :0x7ffff0189b70>
코드는 오류 없이 실행되며 두 포인터의 주소가 다릅니다.
위의 논의를 간단히 말하면 다음과 같이 결론을 내릴 수 있다.
1. 정수 값 = 5; // const가 아닌 값
2. const int *ptr_1 = &value; // ptr_1은 const int 값을 가리키므로 이는 const 값에 대한 포인터입니다.
3. int *const ptr_2 = &value; // ptr_2는 int를 가리키므로 이는 const가 아닌 값에 대한 const 포인터입니다.
4. const int *const ptr_3 = &value; // ptr_3은 const int 값을 가리키므로 이는 const 값에 대한 const 포인터입니다.
상수 방법:
멤버 함수 및 멤버 함수 인수와 마찬가지로 클래스의 객체도 다음과 같이 선언될 수 있습니다. const . const로 선언된 객체는 수정할 수 없으므로 const 멤버 함수만 호출할 수 있습니다. 이러한 함수는 객체를 수정하지 않도록 보장합니다.
통사론:
const Class_Name Object_name;>
- 함수가 const로 선언되면 모든 유형의 객체, const 객체는 물론 const가 아닌 객체에서도 호출될 수 있습니다.
- 객체가 const로 선언될 때마다 선언 시 초기화되어야 합니다. 그러나 선언하는 동안 개체 초기화는 생성자의 도움을 통해서만 가능합니다.
두 가지 방법이 있습니다. 상수 함수 선언:
일반적인 const 함수 선언 :
const void foo() { //void foo() const Not valid } int main() { foo(); }>클래스의 const 멤버 함수 :
class { void foo() const { //..... } }>다음은 상수 함수의 예입니다.
배열과 배열리스트의 차이점C++
// C++ program to demonstrate the // constant function #include using namespace std; // Class Test class Test { int value; public: // Constructor Test(int v = 0) { value = v; } // We get compiler error if we // add a line like 'value = 100;' // in this function. int getValue() const { return value; } // a nonconst function trying to modify value void setValue(int val) { value = val; } }; // Driver Code int main() { // Object of the class T Test t(20); // non-const object invoking const function, no error cout << t.getValue() << endl; // const object const Test t_const(10); // const object invoking const function, no error cout << t_const.getValue() << endl; // const object invoking non-const function, CTE // t_const.setValue(15); // non-const object invoking non-const function, no // error t.setValue(12); cout << t.getValue() << endl; return 0; }> 산출
20 10 12>
const 개체에서 const가 아닌 함수를 호출하려고 하면 다음 오류가 발생합니다.

상수 함수 매개변수 및 반환 유형 :
function() 매개변수 및 function()의 반환 유형은 상수로 선언될 수 있습니다. 이러한 시도는 컴파일 시간 오류를 생성하므로 상수 값을 변경할 수 없습니다.
다음은 위의 접근 방식을 구현하는 C++ 프로그램입니다.
C++ // C++ program to demonstrate the // above approach #include using namespace std; // Function foo() with variable // const int void foo(const int y) { // y = 6; const value // can't be change cout << y; } // Function foo() with variable int void foo1(int y) { // Non-const value can be change y = 5; cout << '
' << y; } // Driver Code int main() { int x = 9; const int z = 10; foo(z); foo1(x); return 0; }> 산출
10 5>
설명: foo() 함수에서 y = 6 명령문을 사용하면 다음 오류가 표시됩니다.
- // y = 6; const 값은 변경하거나 수정할 수 없습니다.

const 반환 유형의 경우 : function()의 반환 유형은 const이므로 const 정수 값을 반환합니다. 다음은 위의 접근 방식을 구현하는 C++ 프로그램입니다.
C++ // C++ program for the above approach #include using namespace std; const int foo(int y) { y--; return y; } int main() { int x = 9; const int z = 10; cout << foo(x) << '
' << foo(z); return 0; }> 산출
8 9>
반환되는 값은 상수 값입니다.
또한 새 복사본이 생성되기 때문에 값으로 전달하는 한 const 또는 non-const 변수를 함수에 전달하는 데 실질적인 문제가 없습니다. 매개변수가 상수가 아닌 함수를 참조하여 상수 변수를 전달하려고 하면 문제가 발생합니다. 이는 다음 오류로 이어지는 const 한정자를 무시합니다.

const 반환 유형 및 const 매개변수의 경우 : 여기서 함수의 반환형과 매개변수는 모두 const형이다. 다음은 위의 접근 방식을 구현하는 C++ 프로그램입니다.
C++ // C++ program for the above approach #include using namespace std; const int foo(const int y) { // y = 9; it'll give CTE error as // y is const var its value can't // be change return y; } // Driver code int main() { int x = 9; const int z = 10; cout << foo(x) << '
' << foo(z); return 0; }> 산출
9 10>
설명: 여기서는 const 값과 const가 아닌 값을 모두 const 매개변수로 함수에 전달할 수 있지만 전달된 변수의 값을 변경할 수는 없습니다. 매개변수가 const이기 때문입니다. 그렇지 않으면 아래와 같은 오류가 발생합니다.
//y=9; y는 const var이므로 값을 변경할 수 없으므로 컴파일 시간 오류가 발생합니다.
