geeksforgeeks-080-c++中的const成员函数

const函数的想法是不允许修改他们调用的对象。如果可能,让尽量多的函数称为const函数,来避免对象的以外修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0) {value = v;}


// in this function.
int () const {return value;}
};

int main() {
Test t(20);
cout<<t.getValue();
return 0;
}

Output:

1
20

当一个函数被声明为const,它可以被任何类型的对象调用。非const函数只能被非cosnt对象调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0) {value = v;}
int () {return value;}
};

int main() {
const Test t;
cout << t.getValue();
return 0;
}

Output:

1
2
 passing 'const Test' as 'this' argument of 'int 
Test::getValue()' discards qualifiers