Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;使某个函数常数?_C++_Oop_Constants - Fatal编程技术网

C++ 如何在C++;使某个函数常数?

C++ 如何在C++;使某个函数常数?,c++,oop,constants,C++,Oop,Constants,我有一个类似这样的类: 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

我有一个类似这样的类:

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
}
MyClass::myFunction(void)const
{
如果(!已加载)
{
//在这里做点什么

loaded=true;/**使用mutable关键字

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

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

哦,天哪……谢谢。我知道有一个非常简单的解决方案。+1:我从来不知道这一点,但需要它很多次。(我使用慢速指针解决方案[bool*loaded=>指针从不变化,但指针后面的值可以改变。)或脏铸液。