這篇文章主要介紹了C++中mutable有什么用,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
代碼編譯運行環(huán)境:VS2017+Win32+Debug
mutalbe的中文意思是“可變的,易變的”,是constant(即C++中的const)的反義詞。在C++中,mutable也是為了突破const的限制而設置的,被mutable修飾的變量將永遠處于可變的狀態(tài)。
mutable的作用有兩點:
(1)保持常量對象中大部分數(shù)據(jù)成員仍然是“只讀”的情況下,實現(xiàn)對個別數(shù)據(jù)成員的修改;
(2)使類的const函數(shù)可以修改對象的mutable數(shù)據(jù)成員。
使用mutable的注意事項:
(1)mutable只能作用于類的非靜態(tài)和非常量數(shù)據(jù)成員。
(2)在一個類中,應盡量或者不用mutable,大量使用mutable表示程序設計存在缺陷。
示例代碼如下:
#includeusing namespace std; //mutable int test;//編譯出錯 class Student { string name; mutable int getNum; //mutable const int test; //編譯出錯 //mutable static int static1;//編譯出錯 public: Student(char* name) { this->name=name; getNum=0; } string getName() const { ++getNum; return name; } void pintTimes() const { cout<
網(wǎng)頁標題:C++中mutable有什么用-創(chuàng)新互聯(lián)
文章轉(zhuǎn)載:http://weahome.cn/article/dchgid.html