簡體   English   中英

如何在C ++中重構一個類來創建一個特定的const函數?

[英]How to refactor a class in C++ to make a certain function const?

我有一個看起來像這樣的類:

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
}

因為我需要設置加載標志,所以該函數現在違反了const限定符。

我有很多代碼存儲常量對象,並且將它們更改為非常量將耗費時間。 此外,這將有點hacky因為我真的希望對象是const。

重構我的類以保持myFunction不變的最佳方法是什么?

PS 加載保護的資源僅用於多個功能,因此提前加載它們不是一個很好的解決方案。

使用mutable關鍵字。

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

這表示加載的成員應該被視為邏輯上的const,但物理上它可能會改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM