C++ 计数器函数不基于以前返回的值

C++ 计数器函数不基于以前返回的值,c++,constructor,while-loop,counter,C++,Constructor,While Loop,Counter,第一个if语句作为可疑输入。该对象调用getCount()函数,但递增的值不是上一个计数,而是0。我尝试在函数中使用Count+=Count int main(){ ......... int displayCount; while(!inputfile.eof()) { inputfile.get(letter); Checker object1; if (object1.isVal

第一个if语句作为可疑输入。该对象调用getCount()函数,但递增的值不是上一个计数,而是0。我尝试在函数中使用Count+=Count

int main(){
    .........     
    int displayCount;
    while(!inputfile.eof()) 
    {

        inputfile.get(letter);

            Checker object1;
            if (object1.isValid(letter)))
            {
                displayCount = object1.getCount();
            }
    }
    cout << displayCount;
   .
   .
   .
Checker::Checker() :
    m_Valid(false),
    count(0)
{
}


int Checker::getCount()
{

    if(m_Valid)
    {
        count ++;
    }

    return count;
}
intmain(){
.........     
int显示计数;
而(!inputfile.eof())
{
inputfile.get(字母);
检查对象1;
if(object1.isValid(字母)))
{
displayCount=object1.getCount();
}
}

cout作为您的注释,
count
不是Check类的staic成员,
Checker object1;
始终创建一个新对象,并将count初始化为
0
。使count静态应该使您的
getCount()
滚动

class Checker
{
   static int count;
};
在Checker.cpp中初始化计数

int Check::count = 0;

您只需将Checker object1移动到循环外部即可;正在创建一个新实例,该实例在代码运行时每次传递的计数均为零。

m\u Valid(false)
然后
if(m\u Valid)
always return false?Billz,它并不总是返回false,因为我有一个单独的函数,在适用时返回true。我仔细检查了代码,如果statment按预期返回true。在头文件中,它被声明为私有访问器“int count”如果您不需要动态创建
object1
,另一个答案比我的好。我不需要动态创建,但我尝试了您的方法。它也很有效。谢谢!