LoginSignup
1

More than 5 years have passed since last update.

何がconstなのかよく忘れるのでメモ

Last updated at Posted at 2018-04-04

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

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
1