如何在 C++ 中重构类 使某个函数成为常量?
我有一个看起来像这样的类:
class MyClass
{
public:
// some stuff omitted
/***
A function which, in itself, is constant and doesn't change the class
***/
void myFunction( void ) const;
private:
/***
If loaded is true, then internal resources are loaded
***/
boolean loaded;
};
因为我以这种方式设计了我的类,所以我被迫这样做:
MyClass :: myFunction( void ) const
{
if( !loaded )
{
// do something here
loaded = true; /** <-- this violates const **/
}
// carry out some computation
}
因为我需要设置 loaded 标志,所以该函数现在违反了 const预选赛。
我有很多存储常量对象的代码,将它们更改为非常量对象将非常耗时。 此外,这会有点hacky,因为我真的希望对象是常量的。
为了保持 myFunction 不变,重构我的类的最佳方法是什么?
PS 由 loaded 保护的资源只有几个功能需要,因此提前加载它们并不是一个很好的解决方案。
I have a class which looks something like this:
class MyClass
{
public:
// some stuff omitted
/***
A function which, in itself, is constant and doesn't change the class
***/
void myFunction( void ) const;
private:
/***
If loaded is true, then internal resources are loaded
***/
boolean loaded;
};
Because I designed my class this way I am forced to do this:
MyClass :: myFunction( void ) const
{
if( !loaded )
{
// do something here
loaded = true; /** <-- this violates const **/
}
// carry out some computation
}
Because I need to set loaded flag the function now violates const qualifier.
I have a lot of code that stores constant objects and it will be time consuming to go round and change them to non-const. Moreover, this will be slightly hacky since I really want the objects to be const.
What is the best way to refactor my class in order to keep myFunction constant?
P.S. The resources guarded by loaded are required only for several functions and therefore loading them in advance is not a very good solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用可变关键字。
这表示加载的成员应该被视为逻辑上常量,但物理上它可能会发生变化。
Use the mutable keyword.
This says that the loaded member should be treated as being logically const but that physically it may change.