c++のconstの話。
constがくっつく場所で「何がconstなのか」が変わりますが
よく忘れるので情報を整理。
変数編
const int
変数hogeの値がconst。
const int hoge = 1;
hoge= 2; // NG
const int* , int const*
ポインタ変数hogeが指し示す先の値がconst。
hoge自体の値はconstじゃない。
int a = 1;
int b = 10;
const int* hoge = &a;
*hoge = 2; // NG
hoge = &b // OK
int* const
ポインタ変数hogeの値がconst。
hogeが指し示す先の値はconstじゃない。
int a = 1;
int b = 10;
int* const hoge = &a;
*hoge = 2; // OK
hoge = &b // NG
const int* const
ポインタ変数hogeとhogeが指し示す先の値がconst。
int a = 1;
int b = 10;
const int* const hoge = &a;
*hoge = 2; // NG
hoge = &b // NG
const int& (参照)
参照hogeの値がconst。
int a = 1;
const int& hoge = a;
hoge = 2; // NG
関数編
constメンバ関数
クラスのメンバ関数にconstが付くと、
そのメンバ関数はクラスの状態を変更しないという宣言になる。
const修飾されたクラス型のインスタンスから呼び出すことができる。
class Sample {
public:
void func1() {};
void func2() const {}; // constメンバ関数
};
const Sample s;
s.func1(); // NG
s.func2(); // OK