C mutable關(guān)鍵字如何使用?
01—mutable關(guān)鍵字詳解與實戰(zhàn)
在C 中mutable關(guān)鍵字是為了突破const關(guān)鍵字的限制,被mutable關(guān)鍵字修飾的成員變量永遠(yuǎn)處于可變的狀態(tài),即使是在被const修飾的成員函數(shù)中。
在C 中被const修飾的成員函數(shù)無法修改類的成員變量,成員變量在該函數(shù)中處于只讀狀態(tài)。然而,在某些場合我們還是需要在const成員函數(shù)中修改成員變量的值,被修改的成員變量與類本身并無多大關(guān)系,也許你會說,去掉函數(shù)的const關(guān)鍵字就行了。可問題是,我只想修改某個變量的值,其他變量希望仍然被const關(guān)鍵字保護(hù)。現(xiàn)在有個場景,我們想獲取函數(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ù)里對成員變量count進(jìn)行加1處理,可是getValue被關(guān)鍵字const修飾啊,無法修改count的值。這個時候mutable派上用場了!我們用mutable關(guān)鍵字修飾count,完整代碼如下:#include?
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計數(shù),編譯運行輸出如下:5
既保護(hù)了其他成員變量,又能達(dá)到我們單獨修改成員變量count值的目的。版權(quán)申明:內(nèi)容來源網(wǎng)絡(luò),版權(quán)歸原創(chuàng)者所有。除非無法確認(rèn),都會標(biāo)明作者及出處,如有侵權(quán)煩請告知,我們會立即刪除并致歉。謝謝!