matable的作用


#include <iostream>
//------mutable 
/*在C++中,mutable是为了突破const的限制而设置的。
被mutable修饰的变量,将永远处于可变的状态,
即使在一个const函数中,甚至结构体变量或者类对象为const,
其mutable成员也可以被修改。*/
struct st
{
    int i_numA;
    mutable int i_numB;
};
/*mutable在类中只能够修饰非静态数据成员。
mutable 数据成员的使用看上去像是骗术,
因为它能够使const函数修改对象的数据成员。
明智地使用 mutable 关键字可以提高代码质量,
因为它能够让你向用户隐藏实现细节,而无须使用不确定的东西。
如果类的成员函数不会改变对象的状态,
那么这个成员函数一般会声明成const的。但是,有些时候,
我们需要在const的函数里面修改一些跟类状态无关的数据成员,
那么这个数据成员就应该被mutalbe来修饰。*/

class Test
{
public:
    Test():m_times(0),m_che(0){}
    void Output() const
    {
        ++m_times;
        //++m_che;
        //error C3490: 由于正在通过常量对象访问“m_che”,因此无法对其进行修改
        std::cout << "Output " << m_times << " times" << std::endl;
    }
private:
    mutable int m_times ;
    int m_che;
};


int main()
{
    const st st1 = { 12, 34 };
    std::cout << st1.i_numA << " " << st1.i_numB << '\n';
    //st1.i_numA = 10;
    //error C3892: “st1”: 不能给常量赋值
    st1.i_numB = 10;
    std::cout << st1.i_numA << " " << st1.i_numB << '\n';

    Test test;
    test.Output();
    test.Output();
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值