const type qualifier soon after the function name

This question already has an answer here:

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

  • $9.3.1/3 states-

    "A nonstatic member function may be declared const, volatile, or const volatile. These cvqualifiers affect the type of the this pointer (9.3.2). They also affect the function type (8.3.5) of the member function; a member function declared const is a const member function, a member function declared volatile is a volatile member function and a member function declared const volatile is a const volatile member function."

    So here is the summary:

    a) A const qualifier can be used only for class non static member functions

    b) cv qualification for function participate in overloading

    struct X{
       int x;
       void f() const{
          cout << typeid(this).name();
          // this->x = 2;  // error
       }
       void f(){
          cout << typeid(this).name();
          this->x = 2;    // ok
       }
    };
    
    int main(){
       X x;
       x.f();         // Calls non const version as const qualification is required
                      // to match parameter to argument for the const version
    
       X const xc;
       xc.f();        // Calls const version as this is an exact match (identity 
                      // conversion)
    }
    

    The const qualifier at the end of a member function declaration indicates that the function can be called on objects which are themselves const. const member functions promise not to change the state of any non-mutable data members.

    const member functions can also, of course, be called on non-const objects (and still make the same promise).

    Member functions can be overloaded on const-ness as well. For example:

    class A {
      public:
        A(int val) : mValue(val) {}
    
        int value() const { return mValue; }
        void value(int newVal) { mValue = newVal; }
    
      private:
        int mValue;
    };
    
    A obj1(1);
    const A obj2(2);
    
    obj1.value(3);  // okay
    obj2.value(3);  // Forbidden--can't call non-const function on const object
    obj1.value(obj2.value());  // Calls non-const on obj1 after calling const on obj2
    

    It means that it doesn't modify the object, so you can call that method with a const object.

    ie

    class MyClass {
    public:
       int ConvertToInteger() const;
    
    };
    

    Means that if you have

    const MyClass myClass;
    

    you can call

    int cValue = myClass.ConvertToInteger();
    

    without a compile error, because the method declaration indicates it doesn't change the object's data.

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

    上一篇: Const在C ++函数声明结束时

    下一篇: 函数名称后不久的const类型限定符