如何在 C++ 中重构类 使某个函数成为常量?

发布于 2024-07-16 15:25:32 字数 805 浏览 6 评论 0原文

我有一个看起来像这样的类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静若繁花 2024-07-23 15:25:32

使用可变关键字。

class MyClass
{
public:
  void myFunction( void ) const;
private:
  mutable boolean loaded;
};

这表示加载的成员应该被视为逻辑上常量,但物理上它可能会发生变化。

Use the mutable keyword.

class MyClass
{
public:
  void myFunction( void ) const;
private:
  mutable boolean loaded;
};

This says that the loaded member should be treated as being logically const but that physically it may change.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文