const成員函數、const類對象、mutable資料成員

來源:互聯網
上載者:User
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成員函數中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.