靜態(tài)成員
類可以包含靜態(tài)成員數(shù)據(jù)和成員函數(shù)。當(dāng)數(shù)據(jù)成員被聲明為“靜態(tài)”時(shí),只會(huì)為類的所有對(duì)象保留一個(gè)數(shù)據(jù)副本。
靜態(tài)數(shù)據(jù)成員不是給定的類類型的對(duì)象的一部分。因此,靜態(tài)數(shù)據(jù)成員的聲明不被視為一個(gè)定義。在類范圍中聲明數(shù)據(jù)成員,但在文件范圍內(nèi)執(zhí)行定義。這些靜態(tài)類成員具有外部鏈接。下面的示例闡釋了這一點(diǎn):
// static_data_members.cppclass BufferedOutput{public: // Return number of bytes written by any object of this class. short BytesWritten() { return bytecount; } // Reset the counter. static void ResetCount() { bytecount = 0; } // Static member declaration. static long bytecount;};// Define bytecount in file scope.long BufferedOutput::bytecount;int main(){}
在前面的代碼中,該成員 bytecount 在類 BufferedOutput 中聲明,但它必須在類聲明的外部定義。
在不引用類類型的對(duì)象的情況下,可以引用靜態(tài)數(shù)據(jù)成員。可以獲取使用 BufferedOutput 對(duì)象編寫的字節(jié)數(shù),如下所示:
long nBytes = BufferedOutput::bytecount;
對(duì)于存在的靜態(tài)成員,類類型的所有對(duì)象的存在則沒有必要。還可以使用成員選擇(. 和 –>)運(yùn)算符訪問靜態(tài)成員。例如:
BufferedOutput Console;long nBytes = Console.bytecount;
在前面的示例中,不會(huì)評(píng)估對(duì)對(duì)象(Console) 的引用;返回的值是靜態(tài)對(duì)象 bytecount 的值。
靜態(tài)數(shù)據(jù)成員遵循類成員訪問規(guī)則,因此只允許類成員函數(shù)和友元擁有對(duì)靜態(tài)數(shù)據(jù)成員的私有訪問權(quán)限。
可變數(shù)據(jù)成員
此關(guān)鍵字只能應(yīng)用于類的非靜態(tài)和非常量數(shù)據(jù)成員。如果某個(gè)數(shù)據(jù)成員被聲明為 mutable,則從 const 成員函數(shù)為此數(shù)據(jù)成員賦值是合法的。
語法
mutable member-variable-declaration;
備注
例如,以下代碼在編譯時(shí)不會(huì)出錯(cuò),因?yàn)?m_accessCount 已聲明為 mutable,因此可以由 GetFlag 修改,即使 GetFlag 是常量成員函數(shù)。
// mutable.cppclass X{public: bool GetFlag() const { m_accessCount++; return m_flag; }private: bool m_flag; mutable int m_accessCount;};int main(){}