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

后端 未结 10 2310
无人共我
无人共我 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:13

    I would like to add the following point.

    You can also make it a const & and const &&

    So,

    struct s{
        void val1() const {
         // *this is const here. Hence this function cannot modify any member of *this
        }
        void val2() const & {
        // *this is const& here
        }
        void val3() const && {
        // The object calling this function should be const rvalue only.
        }
        void val4() && {
        // The object calling this function should be rvalue reference only.
        }
    
    };
    
    int main(){
      s a;
      a.val1(); //okay
      a.val2(); //okay
      // a.val3() not okay, a is not rvalue will be okay if called like
      std::move(a).val3(); // okay, move makes it a rvalue
    }
    
    

    Feel free to improve the answer. I am no expert

提交回复
热议问题