在c++ primer中对于常最函数的解析如下:
- By default, the type of
thisisa const pointertononconst versionof 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
thisshould be a pointer to const. The language resolves this problem by letting this us put const after the parameter list of a member function. Aconstfollowing 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指针,这同时也可以解释在常量函数中为什么不能修改成量变量的值。
本文解析了C++中常量函数的概念及其作用。详细介绍了this指针如何被编译器绑定,以及如何通过在成员函数参数列表后添加const关键字来指示此函数不改变对象状态。

7269

被折叠的 条评论
为什么被折叠?



