C++常量成员函数

通过引用或通过指针传递给函数的形参可能会被该函数修改。但是如果在形参中使用 const 关键字,则可以防止调用的函数修改它。

例如,某个函数的声明如下:

void fun (const string &str);

该函数釆用了一个字符串对象的引用作为形参,但不能修改该对象。有一个类似的机制,可以用来保护隐含的形参 *this,使它不会被成员函数修改。当定义成员函数时,可以在形参列表后面放置 const 关键字,这实际上就是告诉编译器,该成员函数未被允许修改其对象。如果成员函数定义在类外面,则类内的声明和类外的定义都必须具有 const,示例如下:
  1. class ConstExample
  2. {
  3. int x;
  4. public:
  5. ConstExample(int a){ x = a;}
  6. void setValue(int);
  7. int getValue() const;
  8. };
getValue 函数定义语句应如下:
  1. int ConstExample::getValue() const
  2. {
  3. return x;
  4. }
具有常量形参 X 的函数无法转向,并将 X 作为非常量形参传递给另一个函数。换句话说,承诺不修改 X 的函数不能将X传递给另一个函数,除非第二个函数也承诺不修改 X。这种情况有时也可能会以不明显的方式发生。

以下程序使用带有常量形参的函数来打印数组的第一个元素,但是它不会编译,因为它在 const 的使用方面不一致:
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class K
  5. {
  6. public:
  7. void output () // 丢矢了 const
  8. {
  9. cout << "Output of a K object" << endl;
  10. }
  11. };
  12. void outputFirst(const K arr[])
  13. {
  14. arr[0] .output ();
  15. }
  16. int main(int argc, char** argv)
  17. {
  18. K arr [] = { K() };
  19. outputFirst(arr);
  20. return 0;
  21. }
该程序之所以不能编译,是因为编译器不能保证 const 数组的元素在作为隐含的 this 形参传递给 output 成员函数时不会被修改:

arr[0].output();

要让该程序可以编译,则可以使 output() 成员函数变成一个 const 成员函数,以表示它有一个作为常量的 this 形参,示例如下:
  1. class K
  2. {
  3. public:
  4. void output() const
  5. {
  6. cout << "Output of a K object" << endl;
  7. }
  8. };