mutable的用法
很多人看到這個(gè)c++關(guān)鍵字很迷茫。不知道怎么使用。
先簡要說明一下,這個(gè)關(guān)鍵字只能用于非靜態(tài)和非常量數(shù)據(jù)成員。如果一個(gè)類的成員被指定為mutable類型,那么調(diào)用const成員函數(shù)就可以為這個(gè)聲明為mutalbe類型的成員賦值。
下面看一個(gè)例子:
class A
{
public:
bool flag;
void test() const
{
flag = true;
}
};
void main()
{
A a;
a.test();
}
{
public:
bool flag;
void test() const
{
flag = true;
}
};
void main()
{
A a;
a.test();
}
放在編譯器下,出現(xiàn)如下錯(cuò)誤:
--------------------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)
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即可。
posted on 2007-07-10 17:19 AlanTop 閱讀(1427) 評論(4) 編輯 收藏 引用 所屬分類: C++