函数被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;
}

 什么函数用const修饰?

不更改类成员变量的函数,如只读函数。

posted @ 2020-02-01 22:09  夕西行  阅读(287)  评论(0编辑  收藏  举报