[C++基礎]013_神奇的const

來源:互聯網
上載者:User

const這個關鍵字大家肯定都很熟悉,它的意思就是,被我修飾(保護)的東西,你不能改,下面來研究一下它!

1. 常量 

1 int main(){2     const int value = 1;3     value = 2;4     return 0;5 }

上面的代碼是會報錯的,被const修飾的value是無法修改的。

2. 常成員函數

 1 class Test{ 2 public: 3     void test() const{  4         i = 1; 5         j = 2; 6     } 7 private: 8     int i; 9     int j;10 };

上面的代碼是會報錯的,常成員函數是不能修改類的成員變數的。

3. 常對象和常成員函數

 1 #include <iostream> 2 using namespace std; 3  4 class Test{ 5 public: 6     void test() const{  7         cout<<"const function"<<endl; 8     } 9     void test1(){10         cout<<"test1 function"<<endl;11     }12 private:13     int i;14     int j;15 };16 17 18 int main(){19     const Test t;20     t.test();21     t.test1();22 23     return 0;24 }

上面的代碼是會報錯的,t.test1();這段代碼報的錯,因為test1()不是個常成員函數,所以會報錯!-------常對象只能調用其常成員函數。

4. 常量形參

 1 #include <iostream> 2 using namespace std; 3  4 int testFunc(const int& value){ 5     value = 12; 6     return value; 7 } 8  9 int main(){10     int value = 1;11     testFunc(value);12     return 0;13 }

上面的代碼是會報錯的,因為testFunc()的形參是const的,無法修改。

5. 其他常

1 class Test{2 public:3     const void test(){ 4         cout<<"const function"<<endl;5     }6 private:7     int i;8     int j;9 };

上面的代碼在test()前加了const,實際上這樣是毫無效果的,即使void是int也沒有用,這種定義就是閑的蛋疼。

 1 #include <iostream> 2 using namespace std; 3  4 class Test{ 5 public: 6     Test(){ 7         instance = new Test(); 8     } 9     const Test& test(){ 10         cout<<"const function"<<endl;11         return *instance;12     }13 private:14     Test *instance;15 };16 17 int main(){18 19     return 0;20 }

上面的代碼就有意義了,返回的instance不能被修改。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.