LoginSignup
13
11

More than 5 years have passed since last update.

class と const宣言

Last updated at Posted at 2014-06-15

classとconst宣言
C++メモ(個人的なメモです.間違っているかも)

constメンバ関数

constメンバ関数は, オブジェクト内部が変更されない事を宣言する(ただしconst_cast指定された場合を除く:追記中)
そのためconstメンバ関数でメンバ変数を変更する記述は,コンパイルエラーとなる

class ABC{
private:
  int value;

public:
  ABC()              : value(0){} // Default Constructor
  ABC(const ABC &abc): value(0){  // Copy    Constructor
    value = abc.value;
  } 
  ABC(int val)  : value(val){ 
    cout << "preset(value) = " << value << endl;
  }

  /// 
  void  add(int val){        // 非const関数
    value += val;
    cout << "add value = " << value << endl;
  }

  /// 
  void  add(int val)  const{ // const関数 オブジェクトを変更しない
    //value += val; // コンパイルエラー
    cout << "value = " << value << endl;
  }
};

const修飾されたクラスオブジェクト変数 と,constメンバ関数

const修飾されたクラスオブジェクト変数は, オブジェクト内部が改変されない事を保障しなければならない(ただしconst_cast指定された場合を除く:追記中)
そこで C++ではこのような場合,その constメンバ関数のみの呼出しのみ許可することによって行っている.

#include<iostream>
using namespace std;

class ABC{
private:
  int value;

public:
  ABC()              : value(0){} // Default Constructor
  ABC(const ABC &abc): value(0){  // Copy    Constructor
    value = abc.value;
  } 
  ABC(int val) : value(val){ 
    cout << "preset(value) = " << value << endl;
  }

  void  add(int val){        // 非const版 add()関数
    value += val;
    cout << "[     ]add value = " << value << endl;
  }

  void  add(int val)  const{ // const版 add()関数 オブジェクトを変更しない
    //value += val; // コンパイルエラー
    cout << "[Const]add value = " << value << endl;
  }
};

///
///
int main(){
        ABC abc(100);       // const修飾 なし
  const ABC abc_const(200); // const修飾 有り

  abc.add(10);              // 非const版 add()を呼び出し)
  abc_const.add(10);        // const版  add()を呼び出し)
  //       :
  //       :
};

以下のようにconstメンバ関数の定義箇所を外した状態で,const修飾されたクラスオブジェクト変数を定義すると,コンパイルエラー

#include <iostream>
using namespace std;

class ABC{
private:
  int value;

public:
  ABC()              : value(0){} // Default Constructor
  ABC(const ABC &abc): value(0){  // Copy    Constructor
    value = abc.value;
  } 
  ABC(int val)  : value(val){ 
    cout << "preset(value) = " << value << endl;
  }

  void  add(int val){        // 非const関数
    value += val;
    cout << "add value = " << value << endl;
  }

  /***
  ///void  add(int val)  const{ // const関数 オブジェクトを変更しない
  ///  //value += val; // コンパイルエラー
  ///  cout << "value = " << value << endl;
  ///}
  ***/

};

///
///
int main(){
        ABC abc(100);       // OK          (非constのaddを呼び出し)
//const ABC abc_const(200); // コンパイルエラー(非constのaddが呼び出されるため,またはconstのaddが無いため)
       :
       :
};
13
11
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11