蠢萌喵 2021-09-07 10:45 采纳率: 66.7%
浏览 29
已结题

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

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;
}
  • 写回答

2条回答 默认 最新

  • baidu_30233079 2021-09-07 10:54
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月15日
  • 已采纳回答 9月7日
  • 创建了问题 9月7日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度