在c++ primer中对于常最函数的解析如下:
- By default, the type of
this
isa const pointer
tononconst version
of the class type. However, in the case, we cannot bind this to a const object. And means we cannot call an ordinary member function on a const object. - There is no place to indicate that
this
should be a pointer to const. The language resolves this problem by letting this us put const after the parameter list of a member function. Aconst
following the parameter list indicates that this is a pointer to const.
解析
- 在默认情况下,
this
是一个指向非const类型的const指针,那么,在这种情况下this
不能绑定在一个const对象上,也就意味着我们不能调用const对象的常规成员函数。Note:this
指针的绑定是由编译器指执行的,可以理解为Class_Name::member(&object)
,同时this = &object,此时this是Class_Name *const
- 由于
this
是由编译器绑定的,我们不能直接定义this
的类型,cpp中使用常量函数这种形式来指示在此函数中this
为一个指向const类型的const指针,这同时也可以解释在常量函数中为什么不能修改成量变量的值。