Meaning of 'const' last in a function declaration of a class?

后端 未结 10 2117
无人共我
无人共我 2020-11-21 06:37

What is the meaning of const in declarations like these? The const confuses me.

class foobar
{
  public:
     operator int () const         


        
10条回答
  •  我寻月下人不归
    2020-11-21 07:17

    These const mean that compiler will Error if the method 'with const' changes internal data.

    class A
    {
    public:
        A():member_()
        {
        }
    
        int hashGetter() const
        {
            state_ = 1;
            return member_;
        }
        int goodGetter() const
        {
            return member_;
        }
        int getter() const
        {
            //member_ = 2; // error
            return member_;
        }
        int badGetter()
        {
            return member_;
        }
    private:
        mutable int state_;
        int member_;
    };
    

    The test

    int main()
    {
        const A a1;
        a1.badGetter(); // doesn't work
        a1.goodGetter(); // works
        a1.hashGetter(); // works
    
        A a2;
        a2.badGetter(); // works
        a2.goodGetter(); // works
        a2.hashGetter(); // works
    }
    

    Read this for more information

提交回复
热议问题