函数被const修饰,const修饰的究竟是谁?

const修饰,意味着不可更改,即只读。那么const修饰函数时,是谁不可更改?是形参吗?

其实本质上,const修饰的是函数隐含的this指针,this所指向的内存空间不可更改。如下案例中属性x,y不可更改,形参a,b可更改。因为形参在函数被调用时才分配内存。

class Test
{
    void Func(int a,int b) const { ... }  //void Func(const Test* this,int a,int b) const { ... }
private:
  int x;
  int y;
}
原文地址:https://www.cnblogs.com/xixixing/p/12250437.html