gho*_*der 2 c++ inheritance const mutable
我有一些const/mutable和protected的问题.也许这些让我感到困惑所以我会举一个例子.
class Base
{
virtual void foo() const ;
protected :
void bar( int y ){ d_x = y } ;
private :
mutable int d_x ;
}
Run Code Online (Sandbox Code Playgroud)
所以基类有虚拟foo.
class Derived : public Base
{
void foo() const { bar(5); }
private :
mutable int d_x ;
}
Run Code Online (Sandbox Code Playgroud)
所以在我的派生类中,我实现了foo哪个类bar然后写入私有d_x.
我认为很好 - 但编译器说:
passing 'Derived' as 'this' argument of bar discards qualifier.
Run Code Online (Sandbox Code Playgroud)
这是为什么?我认为通过使用mutable我可以使我的成员函数成为const.
从const限定函数(例如foo)内部,您只能调用其他const限定函数.并且bar不是const限定函数.
事实bar只是触及d_x是无关紧要的.可变性d_x仅意味着const限定成员函数可以直接修改它.并且正式地,bar允许修改任何成员(如果它们存在).