class c { int i; void fun1() { i = 5; } void fun2() const { i = 6; } //error C2166: l-value specifies const object }//An attempt was made to modify an item declared with const type
编译的时候编译器回做自动检测的 如果你在const成员函数中修改了成员变量将无法编译通过 但是可以把要修改的成员变量声明为mutable来跳过这个限制 比如: (无法编译通过 违反了常量成员函数的定义) class test { public: test(): m_n(0) {}; void SetV(int n) { m_n = n; }; int GetV() const { m_n = 99; return m_n; }; private: int m_n; };而这样就可以编译通过 对m_n跳过了const成员函数的检测 class test { public: test(): m_n(0) {}; void SetV(int n) { m_n = n; }; int GetV() const { m_n = 99; return m_n; }; private: mutable int m_n; };
{
int i; void fun1()
{ i = 5; } void fun2() const
{ i = 6; } //error C2166: l-value specifies const object
}//An attempt was made to modify an item declared with const type
比如: (无法编译通过 违反了常量成员函数的定义)
class test {
public:
test(): m_n(0) {};
void SetV(int n) { m_n = n; };
int GetV() const { m_n = 99; return m_n; };
private:
int m_n;
};而这样就可以编译通过 对m_n跳过了const成员函数的检测
class test {
public:
test(): m_n(0) {};
void SetV(int n) { m_n = n; };
int GetV() const { m_n = 99; return m_n; };
private:
mutable int m_n;
};