mutable在C++中的作用

简单来说就是为了让类内的const函数可以修改成员变量

我们都知道,类内的const函数不能修改成员变量的值,然而开发过程中往往遇到需要计数或者其他需要变更变量的情况,此时mutable的作用就出现了,它能够让const函数修改被mutable的变量,编译器不会编译报错,例子如下

class student

{

void show () const;

}

void student :: show() const

{

cout << "no thing" << endl;

}        

int main()

{

student s1;

s1.show();

}

定义一个student对象,然后调用了show方法,show方法只是打印输出,并没有修改任何变量,所以可以声明为const,开发过程中如果需要记录打印次数,此时但是const并不能修改打印次数变量,此时可以使用mutable

class student

{

public:

void show () const;

mutable int count;

}

void student :: show() const

{

cout << "no thing" << endl;

count ++

cout << count << endl;

}        

int main()

{

student s1;

s1.show();

}

以上只是一个简单示例,如果需要运行,可以继续补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值