1. 类的成员函数声明为const类型,在类外定义的时候,也需要添加const
2. 如果常成员函数修改了成员变量,会在编译的时候检查出来错误!
其实关于const用错的报错都是在编译阶段出现的!(大胆推测)
3. 类的对象定义为const类型之后,就只允许调用const修饰过的(常成员)函数,否则编译的时候报错;
即使有些成员函数不修改任何成员变量,没有const修饰,也无法被const类型的对象调用!
综上,const类型对象调用成员函数其实需要检查两步:
① 是否有const修饰
② 是否修改了成员变量
4. 2和3说的常成员函数不能修改成员变量,但是有一个例外:假如成员变量被mutable修饰,就可以在常成员函数中修改!
5. 普通成员函数可以调用常成员函数,常成员函数只能调用常成员函数!