绕过 C++ 的常量性派生类中的方法
我必须使用一个将重要的钩子方法定义为 const 的框架,就像这样
class FrameworkClass {
...
virtual void OnEventA(unsigned value) const;
...
}
在我的派生类中,我必须保存通过钩子获得的值
class MyClass: public FrameworkClass
{
...
virtual void OnEventA(unsigned value) const { savedValue = value; } // error!
private:
unsigned savedValue;
}
不幸的是我无法更改框架。
有没有一个好的方法来解决钩子方法的常量性?
I have to use a framework which defines an important hook method as const, like this
class FrameworkClass {
...
virtual void OnEventA(unsigned value) const;
...
}
In my derived class I have to save the value that I get through the hook
class MyClass: public FrameworkClass
{
...
virtual void OnEventA(unsigned value) const { savedValue = value; } // error!
private:
unsigned savedValue;
}
Unfortunately I can't change the framework.
Is there a good way to get around the const'ness of the hook method ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使变量可变:
可变无符号savedValue;
Make the variable mutable:
mutable unsigned savedValue;
mutable
是太“广泛”的解决方法,因为会影响正确使用常量的方法。为了解决不适当的 const'ness,有const_cast
:mutable
is too "broad" workaround because affects methods that use const'ness correctly. to workaround inappropriate const'ness there'sconst_cast
: