mutable關(guān)鍵字詳解與實(shí)戰(zhàn)
在C++中mutable關(guān)鍵字是為了突破const關(guān)鍵字的限制,被mutable關(guān)鍵字修飾的成員變量永遠(yuǎn)處于可變的狀態(tài),即使是在被const修飾的成員函數(shù)中。
在C++中被const修飾的成員函數(shù)無法修改類的成員變量,成員變量在該函數(shù)中處于只讀狀態(tài)。然而,在某些場(chǎng)合我們還是需要在const成員函數(shù)中修改成員變量的值,被修改的成員變量與類本身并無多大關(guān)系,也許你會(huì)說,去掉函數(shù)的const關(guān)鍵字就行了。可問題是,我只想修改某個(gè)變量的值,其他變量希望仍然被const關(guān)鍵字保護(hù)。
現(xiàn)在有個(gè)場(chǎng)景,我們想獲取函數(shù)被調(diào)用的次數(shù),代碼如下:
class Widget{ public: Widget(); ~Widget() = default; int getValue() const; int getCount() const; private: int value; int count; };
這里我們想要獲取getValue函數(shù)被調(diào)用次數(shù),普遍的做法是在getValue函數(shù)里對(duì)成員變量count進(jìn)行加1處理,可是getValue被關(guān)鍵字const修飾啊,無法修改count的值。這個(gè)時(shí)候mutable派上用場(chǎng)了!我們用mutable關(guān)鍵字修飾count,完整代碼如下:
#include 《iostream》 class Widget{ public: Widget(); ~Widget() = default; int getValue() const; int getCount() const; private: int value; mutable int count; }; Widget::Widget() : value(1), count(0) { } int Widget::getValue() const{ count++; return value; } int Widget::getCount() const{ return count; } int main() { Widget w1; for(int i = 0; i 《 5; i++){ w1.getValue(); } std::cout 《《 w1.getCount() 《《 std::endl; return 0; }
被mutable修飾的成員變量count在getValue函數(shù)里進(jìn)行加1計(jì)數(shù),編譯運(yùn)行輸出如下:
5
既保護(hù)了其他成員變量,又能達(dá)到我們單獨(dú)修改成員變量count值的目的。
責(zé)任編輯:haq
原文標(biāo)題:C++ mutable關(guān)鍵字如何使用?
文章出處:【微信號(hào):AndroidPush,微信公眾號(hào):Android編程精選】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論