logo

C++ の const キーワード

この記事では、 const キーワード で見つかります C++ 議論されています。いつでも 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 キーワードを使用するには、次の 3 つの方法が考えられます。

とき 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 型を指す 2 つのポインタ変数ですが、これらの対応する場所に格納されている値は、上で行ったように変更できます。

CSSの最初の子

さもないと 次のエラーが表示されます。 const 変数の値を変更しようとすると、

const ポインタ変数が値を指している場合 :

構文:

  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 引数の値を関数の非 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>

コードはエラーなしで実行され、2 つのポインターのアドレスは異なります。

一言で言えば、上記の議論は次のように結論付けることができます。

1. int 値 = 5; // 非定数値

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 Class_Name Object_name;>
  • 関数が const として宣言されている場合、その関数は、const オブジェクトだけでなく非 const オブジェクトも含め、任意のタイプのオブジェクトに対して呼び出すことができます。
  • オブジェクトを const として宣言する場合は、宣言時に初期化する必要があります。ただし、宣言中のオブジェクトの初期化は、コンストラクターの助けを借りてのみ可能です。

2つの方法があります 定数関数 宣言:

通常の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 関数を呼び出そうとすると、次のエラーが発生します。

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 変数または非 const 変数を関数に渡すことに実質的な問題はありません。問題は、パラメータが非定数である関数への参照によって定数変数を渡そうとしたときに発生します。これにより const 修飾子が無視されるため、次のエラーが発生します。

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 であり、その値は変更できないため、コンパイル時エラーが発生します。