What's the difference between a const member function and a non-const member function?

后端 未结 5 1933
清歌不尽
清歌不尽 2020-11-29 11:17

I am very confused about the const version and non-const version member function like below:

value_type& top() { return this.item }
const value_type&         


        
5条回答
  •  醉梦人生
    2020-11-29 12:00

    The const-qualified member function will be called if the member function is called on an object that is const-qualified.

    The non-const-qualified member function will be called if the member function is called on an object that is not const-qualified.

    For example:

    MyStack s;
    s.top(); // calls non-const member function
    
    const MyStack t;
    t.top(); // calls const member function
    

    Note that the same rules apply when calling a member function on a reference to an object or through a pointer to an object: if the pointer or reference is to a const object, the const member function will be called; otherwise the non-const member function will be called.

提交回复
热议问题