-
#include <iostream>
-
using namespace std;
-
-
class Student{
-
public:
-
void Register()const {
-
m_register = true;
-
}
-
private:
-
bool m_register;
-
};
-
-
int main(int argc, char **argv)
-
{
-
Student *s = new Student();
-
s->Register();
-
return 0;
-
}
错误,因为Register()被const修饰,但是修改了成员变量
m_register
-
1.cpp: In member function ‘void Student::Register() const’:
-
1.cpp:8:22: error: assignment of member ‘Student::m_register’ in read-only object
解决方法:
为了突破const的限制,使用mutable关键字,允许const修饰的函数允许修改被mutable修饰的成员变量
-
#include <iostream>
-
using namespace std;
-
-
class Student{
-
public:
-
void Register()const {
-
m_register = true;
-
}
-
private:
-
mutable bool m_register;//mutable
-
};
-
-
int main(int argc, char **argv)
-
{
-
Student *s = new Student();
-
s->Register();
-
return 0;
阅读(783) | 评论(0) | 转发(0) |