Const declaration of a function

This question already has an answer here:

  • Meaning of “const” last in a C++ method declaration? 7 answers

  • These are member function declarations, presumably, not regular functions.

    const int getNum(int &a, int &b) const;
    

    The leftmost const means that the int being returned from this function is constant. This is a relatively meaningless distinction—sure, the int is constant, but you'll implicitly make a copy of it before using it. This does have an effect on class return types, but it's still not particularly useful.

    The rightmost const means that the member function may be called on a constant object, and that the function is not allowed to modify the object. Effectively, the this pointer inside the function will be constant.

    const int getNum(int &a, int &b);
    

    The const here has the same meaning as the leftmost const in the first example—the return value is constant.

    int getNum(int &a, int &b) const;
    

    The const here has the same meaning as the rightmost const in the first example—the implicit this pointer is constant.


    const int swap(int &a, int &b);
    

    returns an unchangeable value

      int swap(int &a, int &b) const;
    

    returns changeable value, but inside it no one variable can be changed at runtime.

     const int swap(int &a, int &b) const;
    

    the both


    The first and third are const member functions, meaning that they can be called on a const instance, and do not modify any of the instance's fields.

    The first and second have return-type const int , which is not very useful, since they return a temporary value, so there's no point in making that value const .

    链接地址: http://www.djcxy.com/p/40434.html

    上一篇: 为什么在没有参数的方法中使用const?

    下一篇: 一个函数的const声明