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)推薦
Spire.XLS for C++組件說明
![Spire.XLS for <b class='flag-5'>C++</b>組件說明](https://file1.elecfans.com/web3/M00/05/E7/wKgZO2eFwUuAbuoQAAAbn_khf8A091.png)
EE-112:模擬C++中的類實(shí)現(xiàn)
![EE-112:模擬<b class='flag-5'>C++</b><b class='flag-5'>中</b>的類實(shí)現(xiàn)](https://file.elecfans.com/web1/M00/D9/4E/pIYBAF_1ac2Ac0EEAABDkS1IP1s689.png)
C語言關(guān)鍵字分別發(fā)生在哪個(gè)階段
C++新手容易犯的十個(gè)編程錯(cuò)誤
ostream在c++中的用法
使用邊緣AI和Sitara處理器進(jìn)行關(guān)鍵字檢測(cè)
![使用邊緣AI和Sitara處理器進(jìn)行<b class='flag-5'>關(guān)鍵字</b>檢測(cè)](https://file.elecfans.com/web1/M00/D9/4E/pIYBAF_1ac2Ac0EEAABDkS1IP1s689.png)
C++中實(shí)現(xiàn)類似instanceof的方法
![<b class='flag-5'>C++</b><b class='flag-5'>中</b>實(shí)現(xiàn)類似instanceof的方法](https://file1.elecfans.com/web2/M00/FE/0C/wKgaomaYe1CAQ31QAAAnf0IkoSU605.png)
快速掌握C語言關(guān)鍵字
![快速掌握<b class='flag-5'>C</b>語言<b class='flag-5'>關(guān)鍵字</b>](https://file.elecfans.com/web2/M00/9B/3D/poYBAGQjnauAVXOgAABFcEbXdEE684.png)
inline關(guān)鍵字被優(yōu)化導(dǎo)致此類函數(shù)被布局在flash內(nèi),怎么處理?
鴻蒙OS開發(fā)實(shí)例:【Native C++】
![鴻蒙OS開發(fā)實(shí)例:【Native <b class='flag-5'>C++</b>】](https://file1.elecfans.com/web2/M00/C8/31/wKgZomYZMTCAaDv3AAY5x13C324319.jpg)
使用 MISRA C++:2023? 避免基于范圍的 for 循環(huán)中的錯(cuò)誤
![使用 MISRA <b class='flag-5'>C++</b>:2023? 避免基于范圍的 for 循環(huán)中的錯(cuò)誤](https://file1.elecfans.com/web2/M00/A9/66/wKgZomUl7m-AHJX6AABuJjgxs14678.png)
評(píng)論