很多人看到这个c++关键字很迷茫。不知道怎么使用。
先简要说明一下,这个关键字只能用于非静态和非常量数据成员。如果一个类的成员被指定为mutable类型,那么调用const成员函数就可以为这个声明为mutalbe类型的成员赋值。
下面看一个例子:
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();
}
放在编译器下,出现如下错误:
--------------------
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
![dot.gif](https://i-blog.csdnimg.cn/blog_migrate/918e8df969f9f8c8d002f25cda86cade.gif)
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即可。