任何不会修改数据成员的函数都应该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其它非const成员函数,编译器将指出错误,这无疑会提高程序的健壮性。
以下程序中,类stack的成员函数GetCount仅用于计数,从逻辑上讲GetCount应当为const函数。编译器将指出GetCount函数中的错误。class Stack{ public:void Push(int elem);int Pop(void);int GetCount(void) const; // const成员函数 private:int m_num;int m_data[100];};int Stack::GetCount(void) const{ ++ m_num; // 编译错误,企图修改数据成员m_numPop(); // 编译错误,企图调用非const函数return m_num;}const成员函数的声明看起来怪怪的:const关键字只能放在函数声明的尾部,大概是因为其它地方都已经被占用了。