Call a non-const member function from a const member function

后端 未结 7 1725
情深已故
情深已故 2020-12-29 06:15

I would like to know if its possible to call a non-const member function from a const member function. In the example below First gives a compiler error. I understand why it

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 07:01

    It is possible:

    const int& First() const 
    { 
        return const_cast(this)->Second(); 
    }
    
    int& Second() { return m_bar; }
    

    I wouldn't recommend this; it's ugly and dangerous (any use of const_cast is dangerous).

    It's better to move as much common functionality as you can into helper functions, then have your const and non-const member functions each do as little work as they need to.

    In the case of a simple accessor like this, it's just as easy to return m_bar; from both of the functions as it is to call one function from the other.

提交回复
热议问题