mutable关键字有两种不同的用途
1、与const一起使用
2、在lambda表达式中
3、两种情况同时存在
1、与const在类中一起使用
# include <iostream>
using namespace std;
class Entity
{
private:
string m_Name;
mutable int m_DebugCount = 0; //标记类成员为mutable,意味着类中的const方法可以修改这个成员
public:
// 假设为了调试,计算这个函数在程序中被调用了多少次
const string& GetName() const // 函数名后面的const意味着不允许修改实际的类成员
{
m_DebugCount++;
return m_Name;
}
};
int main()
{
const Entity e; // 常量的Entity对象
e.GetName();
cin.get();
return 0;
}