1. const成員函數 只是告訴編譯器,表明不修改類對象. 但是並不能阻止程式員可能做到的所有修改動作,比如對指標的修改,編譯器可能無法檢測到
2. 類體外定義的const成員函數,在定義和聲明處都需要const修飾符 1 class classname
2 {
3 public:
4 classname() {}
5 ~classname();
6
7 void foo()
const;
8 char &operator[](int i);
9 private:
10 //.
11 }
12
13 void classname::foo()
const
14 {
15 //
16 }
17
18 char &classname::operator[](int i)
19 {
20 //..
21 }
22 int main()
23 {
24 const classname obj();
25 obj.foo();//ok
26 obj[2];//error,coz [] not const
27 }
28
3. const對象為常量對象,它只能調用聲明為const的成員函數。但是建構函式和解構函式是唯一不是const成員函數卻可以被const對象調用的成員函數。 當然,一般對象當然也可以調用const成員了 1 class A
2 {
3 public:
4 A(int x, int y) : _x(x), _y(y) {}
5 //int get() { return _x;}
6 int get() const { return _y;}
7 private:
8 int _x, _y;
9 };
10
11 int main()
12 {
13 A obj(2, 3);
14 const A obj1(2, 3);
15 cout << obj.get() << " " << obj1.get();//3 3
16
17 return 0;
18 }
19
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 A(int x, int y) : _x(x), _y(y) {}
8 int get() { return _x;}
9 //int get() const { return _y;}
10 private:
11 int _x, _y;
12 };
13
14 int main()
15 {
16 A obj(2, 3);
17 const A obj1(2, 3);
18 cout << obj.get() << " " << obj1.get();
19 //錯誤,obj1為常量對象,不能調用非const方法
20 return 0;
21 }
4. const成員函數可以被相同參數表的非const成員函數重載 1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 A(int x, int y) : _x(x), _y(y) {}
8 int get() { return _x;}
9 int get() const { return _y;}
10 private:
11 int _x, _y;
12 };
13
14 int main()
15 {
16 A obj(2, 3);
17 const A obj1(2, 3);
18 cout << obj.get() << " " << obj1.get();
19 // 2 3
20 return 0;
21 }
22
4. 為了允許修改一個類的成員變數,即使是一個const對象的資料成員,於是引入了mutable
通過將資料成員聲明為mutable, 表明此成員總是可以被更新,即使在一個const成員函數中。