const 成员函数

来源:互联网 发布:风云无双装备升级数据 编辑:程序博客网 时间:2024/04/30 09:22

任何不会修改数据成员的函数都应该声明为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_num

Pop(); // 编译错误,企图调用非const 函数

xxx//此处报错为:Member function 'xxx' not viable: 'this' argument has type 'xxx', but function is not marked const

return m_num;
}
const 成员函数的声明看起来怪怪的:const 关键字只能放在函数声明的尾部,大
概是因为其它地方都已经被占用了。