Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/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++_Loops - Fatal编程技术网

C++ 在常数函数中递增计数器

C++ 在常数函数中递增计数器,c++,loops,C++,Loops,我试图保留一个计数器,记录while循环运行了多少次。但是,代码是给我的,我不确定用哪种方式修改代码才能增加代码 int findPos( const HashedObj & x ) const { int offset = 1; int currentPos = myhash( x ); while( array[ currentPos ].info != EMPTY && array[ currentPos ].elem

我试图保留一个计数器,记录while循环运行了多少次。但是,代码是给我的,我不确定用哪种方式修改代码才能增加代码

int findPos( const HashedObj & x ) const
{
    int offset = 1;
    int currentPos = myhash( x );

    while( array[ currentPos ].info != EMPTY &&
           array[ currentPos ].element != x )
    {
        currentPos += offset;  // Compute ith probe
        offset += 2;
        incrementCounter++;
        if( currentPos >= array.size( ) )
            currentPos -= array.size( );
    }

    return currentPos;
}
当我编译它时,我得到“incrementCounter无法修改,因为它是通过const对象访问的”


当我看到这一点时,我知道我不能在常量函数中编辑一个值,但我不知道该怎么做。

递增计数器
声明为
可变
,如下所示:

mutable int  incrementCounter;
然后您可以在
findPos
功能中更改它

-
应用于非引用非常量类型的非静态类成员,并指定该成员不影响类的外部可见状态(通常用于互斥锁、备忘录缓存、惰性计算和访问检测)
mutable
常量类实例的成员是可修改的。

(注意:C++语言语法将可更改为存储类说明符,但不影响存储类)


incrementCounter
的定义在哪里?incrementCounter在包含此方法的类的公共定义中声明。您可以使
incrementCounter
成为
mutable
。这就是我正在寻找的答案,并修复了问题。这就是我一直在寻找和解决的问题,我有。