类中const函数及非const函数的调用规则

    xiaoxiao2021-03-25  114

    类中const函数及非const函数的调用规则

    class Student { public: int getAge() { return m_age; }

    int getAge() const { return m_age; } void setAge(int age) { m_age = age; } void setAge(int age) const { //此处报错,提示左值不是const //m_age = age; }

    public: int m_age; };

      众所周知,在相同参数及相同名字的情况下,const是可以构成函数重载的,但const成员函数不能更改任何非静态成员变量; 类中二函数都存在的情况下: const对象默认调用const成员函数,非const对象默认调用非const成员函数; 若非const对象想调用const成员函数,则需显式转化,如(const Student&)obj.getAge(); 若const对象想调用非const成员函数,同理const_cast

    转载请注明原文地址: https://ju.6miu.com/read-15330.html

    最新回复(0)