我想问一下在这里使用可变对象是否合适:
基类是第三方库。我正在扩展它以提供自己的NoMod()。该库原始的NoMod()声明为const。
我的NoMod()与基类不同之处在于它需要修改自己的成员变量。
因此,为了使我的NoMod()编译并在调用Draw()时被调用,我必须:
1) 将Derive::NoMod()实现为const 2) 使我的int y可变。
这是我能做的最好的吗?
#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;
}
基类是第三方库。我正在扩展它以提供自己的NoMod()。该库原始的NoMod()声明为const。
我的NoMod()与基类不同之处在于它需要修改自己的成员变量。
因此,为了使我的NoMod()编译并在调用Draw()时被调用,我必须:
1) 将Derive::NoMod()实现为const 2) 使我的int y可变。
这是我能做的最好的吗?