仿函数中的成员变量的问题

img


使用static不报错,但是运行不了

img


#include <iostream>
#include <string>
using namespace std;

//函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
class MyAdd
{
public:
    int operator()(int a, int b)const
    {
        return a + b;
    }
};

void test01()
{
    MyAdd add;  //这就是创建了一个函数对象
    int c = add(10, 5);
    cout << c << endl;
}

//函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
    int count;
    MyPrint()
    {
        this->count = 0;
    }
    void operator()(string str)const
    {
        cout << str << endl;
        this->count++;
    }
    //static int count;
};

void test02()
{
    MyPrint myprint;
    myprint("Hello World!");
    myprint("Hello World!");
    myprint("Hello World!");
    myprint("Hello World!");
    //cout << myprint.count << endl;
}
int main(void)
{
    //test01();
    test02();

    system("pause");
    return 0;
}

你32行声明为const函数,const函数是不能修改成员变量的。把Const去掉

void operator()(string str)const这里,加了const就不允许对成员变量修改,把const去掉就可以了