C++ mutable

来源:互联网 发布:dts hd mac 编辑:程序博客网 时间:2024/05/21 01:56

mutable 英语翻译是易变的,性情不定的。常看到用来修饰成员函数变量,表示这个函数可以被修改,即使这个变量在const函数中,mutable修饰的变量也能被修改,从而忽略const的限制。

#include <iostream>class CMutable{public:    CMutable(void):m_Count(0){}    ~CMutable(void){}    int countMutable() const    {        m_Count++;        return m_Count;    }private:    mutable int m_Count;};int main(){    CMutable MyMutable;    int Res = MyMutable.countMutable();    return 1;}

在上面类中计算countMutable()中虽然const修饰,但是对象的成员变量m_Count还是可以被修改。但是请注意,mutable的不能用来修饰static和const变量,因为static属于类而不属于具体某个对象,而mutable就是用来表示类对象的某些数据成员在const函数中可以被修改,所以两者无关联。const本就是互斥的,在一起就冲突矛盾了,不能修饰。

【参考资料】
【1】https://msdn.microsoft.com/en-us/library/4h2h0ktk.aspx
【2】http://www.jb51.net/article/42046.htm

0 0