const类型成员函数与mutable
const類型成員函數與mutable
原文:http://houhualiang.i.sohu.com/blog/view/42619368.htm
| ? | const類型的成員函數是指使用const關鍵字進行修飾的類的成員函數。const類型的成員函數對函數內部的操作加以一定的限制,比如不可以對對象的屬性進行修改等,這樣可以提高程序代碼的正確性。 在使用關鍵字const對成員函數修飾的時候,將const放在成員函數的后面。在定義對象的時候,可以使用關鍵字const聲明對象為常量對象。對于常量對象,如果使用非常量成員函數來操作,則會出現一個編譯錯誤;同樣,對于使用關鍵字volatile聲明的對象, 如果使用非volatile類型的成員函數來操作,也會出現一個編譯錯誤。 如果想修改const類型對象的成員變量,可以使用關鍵字mutable對該成員變量進行修飾。 1 #include <iostream.h> 2 #include <conio.h> 3 class CDate 4 { 5 public: 6 int year; 7 mutable int month; // 使用關鍵字mutable進行修飾 8 CDate(int y=2000,int m=1) 9 { 10 year= y; 11 month= m; 12 }; 13 int GetMonth() const; // 一個只讀函數 14 void SetMonth( int m ); // 一個寫函數 15 }; 16 int CDate::GetMonth() const 17 { 18 // 下面一行錯誤,故屏蔽掉 19 // year++; // 但如果是month+ + ;則沒問題 20 return month; // 在只讀函數中不可以進行改寫操作 21 } 22 void CDate::SetMonth(int m) 23 { 24 month = m; // 設置月份 25 } 26 void main() 27 { 28 CDate d1; 29 d1.Setmonth(9); 30 d1.year=1975 ; 31 cout<<"d1:"<<d1.year<<"年"<<d1.Getmonth()<<"月\n"; 32 const CDate d2; 33 d2.month=7; 34 cout<<"d2:"<<d2.year<<"年"<<d2.Getmonth()<<"月\n"; 35 // 下面一句錯誤,故屏蔽掉 36 // d2.SetMonth(7); // 不可以對常量對象調用非常量成員函數 37 // 下面一句錯誤,故屏蔽掉 38 // d2.year=1973; // 不可以修改常量對象的成員變量 39 }運行結果: |
轉載于:https://www.cnblogs.com/lx09110718/p/constmutable.html
總結
以上是生活随笔為你收集整理的const类型成员函数与mutable的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOUtils工具类的依赖maven
- 下一篇: 众多Android 开源项目再次推荐,学