const function, function const

来源:互联网 发布:php网页输出原代码 编辑:程序博客网 时间:2024/05/23 19:19

常量成员函数

const int& myData::getData() const { return data; }
function()后面加const叫做const function,只能在class中作为成员函数使用,可以由const object 或者 non-const object 调用,但const object 只能调用const member function。不修改类中成员变量的函数都可以声明为const member function
const 成员函数可以与 non-const 成员函数重载。
function()前面加const表示返回值是const,可以在任何地方用,只需要接收变量是const就可以。

Reference:

1. 
  • Const functions can always be called
  • Non-const functions can only be called by non-const objects 
  • 【Const Correctness, http://www.cprogramming.com/tutorial/const_correctness.html】