C++:类中成员函数声明后面接 const

const 表示对类中成员函数属性的声明;

表示不会修改类中的数据成员;

在编写const成员函数时,若不慎修改了数据成员,或者调用了其他非const成员函数,编译器将指出错误;

以下程序中,类stack的成员函数GetCount仅用于计数,从逻辑上讲GetCount应当为const函数。

class Stack
{
    public:
    void Push(int elem);
    int Pop(void);
    intGetCount(void) const; // const 成员函数
    private:
    int m_num;
    int m_data[100];
};
int Stack::GetCount(void)const // 注意:在实现的时候需要带有const修饰
{
    ++ m_num; // 编译错误,企图修改数据成员m_num
    Pop();// 编译错误,企图调用非const函数
    returnm_num;
}

关于const函数的几点规则:

a.在类中被const声明的成员函数只能访问const成员函数,而非const函数可以访问任意的成员函数,包括const成员函数

b.在类中被const声明的成员函数不可以修改对象的数据,不管对象是否具有const性质,它在编译时,以是否修改

成员数据为依据,进行检查.

c.加上mutable修饰符的数据成员,对于任何情况下通过任何手段都可修改,自然此时的const成员函数是可以修改它的

转自:https://blog.csdn.net/u013346007/article/details/81287027
我也不知道他转自哪!

猜你喜欢

转载自blog.csdn.net/qit1314/article/details/86631160