我想问一下这里使用 mutable 是否合适:
#include <iostream>
class Base
{
protected:
int x;
public:
virtual void NoMod() const
{
std::cout << x << std::endl;
}
void Draw() const
{
this->NoMod();
}
};
class Derive : public Base
{
private:
mutable int y;
public:
void NoMod() const
{
y = 5;
}
};
int main()
{
Derive derive;
// Test virtual with derive
derive.Draw();
return 0;
}
Base 类是第 3 方库。我正在扩展它以提供我自己的 NoMod()。库原始 NoMod() 被声明为 const。
我的 NoMod() 与 Base 的不同之处在于它需要修改自己的成员变量。
因此,为了让我自己的 NoMod() 编译并在调用 Draw() 时被调用,我必须
1) 将 Derive::NoMod() 实现为 const
2) 使我的 int y 可变。
这是我能做的最好的吗?