#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;
}
matable的作用
最新推荐文章于 2022-11-27 21:40:03 发布