What's the use of const here

前端 未结 7 1835
借酒劲吻你
借酒劲吻你 2021-01-21 13:09

in

int salary() const { return mySalary; }

as far as I understand const is for this pointer, but I\'m not sure. Can any one tell me what is the us

相关标签:
7条回答
  • 2021-01-21 13:16

    It just guarantees that calling salary() doesn't change the object state. IE, it can be called with a const pointer or reference.

    0 讨论(0)
  • 2021-01-21 13:20

    When the function is marked const it can be called on a const pointer/reference of that class. In effect it says This function does not modify the state of the class.

    0 讨论(0)
  • 2021-01-21 13:22

    It's a const member function. It's a contract that the function does not change the state of the instance.

    more here: http://www.fredosaurus.com/notes-cpp/oop-memberfuncs/constmemberfuncs.html

    0 讨论(0)
  • 2021-01-21 13:24

    It means that function can be called on a const object; and inside that member function the this pointer is const.

    0 讨论(0)
  • 2021-01-21 13:30

    Sounds like you've got the right idea, in C++ const on a method of an object means that the method cannot modify the object.

    For example, this would not be allowed:

    class Animal {
       int _state = 0;
    
       void changeState() const { 
         _state = 1;
       }
    }
    
    0 讨论(0)
  • 2021-01-21 13:30

    A const after function of a class, means this function would not modify any member objects of this class. Only one exception, when the member variable is marked with Mutable.

    0 讨论(0)
提交回复
热议问题