从const成员函数中调用非const成员函数

从const成员函数中调用非const成员函数

问题描述:

我想知道是否有可能从const成员函数中调用非const成员函数。在下面的示例中,首先给出了编译器错误。我知道为什么会出现错误,我想知道是否有解决方法。

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 gives an error, I would like to know if there is a way to work around it.

class Foo
{
   const int& First() const
   {
         return Second();
   }

   int& Second()
   {
        return m_bar;
   }

   int m_bar;
}

我真的不想讨论这样做的智慧,我是

I don't really want to discuss the wisdom of doing this, I'm curious if its even possible.

return (const_cast<Foo*>(this))->Second();

然后安静地哭泣。