mutable

mutalbe的中文意思是“可变的,易变的”,跟constant(既C++中的const)是反义词。
在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。
我们知道,如果类的成员函数不会改变对象的状态,那么这个成员函数一般会声明成const的。但是,有些时候,我们需要在const的函数里面修改一些跟类状态无关的数据成员,那么这个数据成员就应该被mutalbe来修饰。

#include <iostream>
using namespace std;
class A {
public:
    A(){}
    ~A(){}

    int change(int value) {
        z = 3;
        return z;
    }

    int add(int a, int b) const {
     // z = 3;    // compile error
        return a + b;
    }

    int minus(int a, int b) const {
        times++;
        return a - b;
    }

private:
    int z;
    mutable int times;
};


int main() {
    A a;
    int result = a.add(3, 2);
    cout << "result:" << result << endl;
    cout << a.change(100) << endl;
    cout << "9 - 7 = " << a.minus(9, 7) << endl;

    return 0;
}

 

------------------------------------------------

 #include <iostream>  
 #include <vector>  
 #include <algorithm>  
 int main()  
 {  
     std::vector<int> v;  
     v.resize(10);  
     std::fill(v.begin(), v.end(), 100);  
     return 0;  
 } 

 

posted @ 2016-01-22 22:00  牧 天  阅读(250)  评论(0)    收藏  举报