C++, Classes, Const, and strange syntax

后端 未结 8 2110
广开言路
广开言路 2020-12-18 02:14

I was re-reading c++ primer(4th ed.) today - the section on member functions and const references etc, and I came up with this wierd little program:

using st         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 02:34

    const qualifier restricts to call non-const methods on your object, so the problem is your design that allows you to give non-const reference to a member by a const method. The common approach is

          Member& getccp()       {return *member;}
    const Member& getccp() const {return *member;} 
    

    In some cases when logical constness of your object don't suffer from external modification of it's member you can allow

          Member& getccp() const {return *member;}
    

    Another example of difference in logical and formal constness is the mutable members. I.e. mutable can be some term that was computed at the last const method's invoke, if you will get the same input at next invoke you can easily return stored value.

提交回复
热议问题