メンバ関数の左にあるconst
返り値をconst指定できます。Wandbox
C++
1int answer = 42;
2
3struct Spam {
4 const int& func() {
5 return answer;
6 }
7} spam;
8
9int main(void) {
10 spam.func() = 0; // エラー! assignment of read-only location 'spam.Spam::func()'
11}
メンバ関数の右にあるconst
当該メンバ関数内ではメンバ変数(mutable除く)がconst指定されます。Wandbox
C++
1struct Spam {
2 void func() const {
3 mutable_val = 42; // mutableメンバ変数はいじっても良い
4 private_val = 42; // エラー! assignment of member 'Spam::private_val' in read-only object
5 }
6
7private:
8 mutable int mutable_val = 0;
9 int private_val = 0;
10};
11
12int main(void) {
13
14}
また、constなメンバ関数と非constなメンバ関数の両方を持つこともできます。
C++
1#include <iostream>
2
3struct Spam {
4 void func() const {
5 std::cout << "const func\n";
6 }
7
8 void func() {
9 std::cout << "normal func\n";
10 }
11};
12
13int main(void) {
14 {
15 const Spam spam;
16 spam.func();
17 }
18 {
19 Spam spam;
20 spam.func();
21 }
22}
実行結果 Wandbox
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/21 12:38