很多人看到這個c++關(guān)鍵字很迷茫。不知道怎么使用。
先簡要說明一下,這個關(guān)鍵字只能用于非靜態(tài)和非常量數(shù)據(jù)成員。如果一個類的成員被指定為mutable類型,那么調(diào)用const成員函數(shù)就可以為這個聲明為mutalbe類型的成員賦值。
下面看一個例子:
class A
{
public:
bool flag;
void test() const
{
flag = true;
}
};
void main()
{
A a;
a.test();
}
放在編譯器下,出現(xiàn)如下錯誤:
--------------------Configuration: Test_muable - Win32 Debug--------------------
Compiling
test.cpp
D:\Datum\Datum\Project\Test_muable\test.cpp(7) : error C2166: l-value specifies const object
Error executing cl.exe.
Test_muable.exe - 1 error(s), 0 warning(s)
看mutable的定義,知道只需把 flag類型前加mutable即可。